未知的错误:对象无效作为一个react子女(找到:带键{key,libelle}的对象):在fetch api上

发布于 2025-02-12 02:19:16 字数 3704 浏览 4 评论 0原文

我尝试添加我的API并获取城镇的名称,以将其放在我的选择标签上。但是我无法理解错误并纠正它。

import React, {useState} from 'react';
import {Navigate} from 'react-router-dom'
import Entete from './MEP/entete'

function Localisation() {
  const [CP, setCP]= React.useState('');
  const [city, setCity]= React.useState('');
  const [ListVille, setList]= React.useState([]);
  const [goToExploit, setGoToExploit] = useState(false)

  function handleSubmit(event) {
    event.preventDefault()
    setGoToExploit(true)
  }

  if(goToExploit) {
      return <Navigate push to={`/exploitation`} />
  }

  function handleChange(event) {
    const CP = event.target.value
    setCP(CP)
    fetch('http://localhost:3000/api/1.0/getCommunes/' + CP ).then(function(response) {
        return response.json()
      }).then(function(response){
        setList(response)
        console.log(response)
      })
      console.log(ListVille)
 }

  return (
    <div>
      <Entete titre="Localisation"/>

      <form onSubmit={handleSubmit}>
        <div className='titre'> Saisissez votre code postal </div>
        <input 
        className='input'
        value={CP}
        onChange={handleChange}
        placeholder='Code Postal'
        type='text'
        required/>
        <div className='titre'> Saisissez votre ville {ListVille}</div>
        <select >
          <option value="">Choisissez</option>
          { Array.isArray(ListVille) ? ListVille.map((item)=>( <option value={item.key} > {item.libelle} </option> ) ) : ListVille===undefined ?  <option value={'pas de ville'}>  </option>  : <option value={ListVille.key}> {ListVille.libelle} </option> }
        </select>
        <div className='centrer'>
          <button type='submit' className='validation'> Valider </button>
        </div>
      </form>
    </div>
  );
}

export default Localisation;

当CP不是API的值时,SELECT仅渲染“ Choisissez”,否则将

在我输入良好CP的第一个Console.log(wendesp)渲染时渲染该镇的列表:

(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {key: '41026', libelle: 'Brévainville'}
1: {key: '41028', libelle: 'Busloup'}
2: {key: '41073', libelle: 'Danzé'}
3: {key: '41095', libelle: 'Fréteval'}
4: {key: '41115', libelle: 'Lignières'}
5: {key: '41141', libelle: 'Moisy'}
6: {key: '41154', libelle: 'Morée'}
7: {key: '41172', libelle: 'Ouzouer-le-Doyen'}
8: {key: '41173', libelle: 'Beauce la Romaine'}
9: {key: '41186', libelle: 'Rahart'}
10: {key: '41214', libelle: 'Saint-Hilaire-la-Gravelle'}
11: {key: '41216', libelle: 'Saint-Jean-Froidmentel'}
12: {key: '41275', libelle: 'La Ville-aux-Clercs'}
length: 13
[[Prototype]]: Array(0)

和第二个Console.log(Listville)(Listville)渲染[]

所有带有错误消息的全部:

Uncaught Error: Objects are not valid as a React child (found: object with keys {key, libelle}). 
If you meant to render a collection of children, use an array instead.

我尝试过:

  • 将获取函数放在使用效果中,但它也不起作用
  • &lt; option key = {item.key} value = {item.key}&gt; {item.libelle}&lt;/option&gt;

有人可以帮助我或引导我做某事吗?

编辑似乎来自Listville Const,因为当我在Mys Render &lt; div className ='pragraphe'&gt中尝试时,测试{cp ==='41160'? Listville [0] .Key:'coucou'}&lt;/div&gt;我已经git错误消息:

Uncaught TypeError: Cannot read properties of undefined (reading 'key')

编辑2 问题似乎来自于setList(wendesp)没有在Listville设置数据,但我无法弄清楚为什么

编辑3 setList(wendesp)确实在Listville设置了数据,但是它的异步是为了设置数据

I try to add my API and fetch the name of the town in it to put it in a my option on my select tag. but I'm not able to understand the mistake and correct it.

import React, {useState} from 'react';
import {Navigate} from 'react-router-dom'
import Entete from './MEP/entete'

function Localisation() {
  const [CP, setCP]= React.useState('');
  const [city, setCity]= React.useState('');
  const [ListVille, setList]= React.useState([]);
  const [goToExploit, setGoToExploit] = useState(false)

  function handleSubmit(event) {
    event.preventDefault()
    setGoToExploit(true)
  }

  if(goToExploit) {
      return <Navigate push to={`/exploitation`} />
  }

  function handleChange(event) {
    const CP = event.target.value
    setCP(CP)
    fetch('http://localhost:3000/api/1.0/getCommunes/' + CP ).then(function(response) {
        return response.json()
      }).then(function(response){
        setList(response)
        console.log(response)
      })
      console.log(ListVille)
 }

  return (
    <div>
      <Entete titre="Localisation"/>

      <form onSubmit={handleSubmit}>
        <div className='titre'> Saisissez votre code postal </div>
        <input 
        className='input'
        value={CP}
        onChange={handleChange}
        placeholder='Code Postal'
        type='text'
        required/>
        <div className='titre'> Saisissez votre ville {ListVille}</div>
        <select >
          <option value="">Choisissez</option>
          { Array.isArray(ListVille) ? ListVille.map((item)=>( <option value={item.key} > {item.libelle} </option> ) ) : ListVille===undefined ?  <option value={'pas de ville'}>  </option>  : <option value={ListVille.key}> {ListVille.libelle} </option> }
        </select>
        <div className='centrer'>
          <button type='submit' className='validation'> Valider </button>
        </div>
      </form>
    </div>
  );
}

export default Localisation;

When the CP is not a value of the API the select render only "choisissez" else it render the list of the town

When I enter a good CP the first console.log(response) render :

(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {key: '41026', libelle: 'Brévainville'}
1: {key: '41028', libelle: 'Busloup'}
2: {key: '41073', libelle: 'Danzé'}
3: {key: '41095', libelle: 'Fréteval'}
4: {key: '41115', libelle: 'Lignières'}
5: {key: '41141', libelle: 'Moisy'}
6: {key: '41154', libelle: 'Morée'}
7: {key: '41172', libelle: 'Ouzouer-le-Doyen'}
8: {key: '41173', libelle: 'Beauce la Romaine'}
9: {key: '41186', libelle: 'Rahart'}
10: {key: '41214', libelle: 'Saint-Hilaire-la-Gravelle'}
11: {key: '41216', libelle: 'Saint-Jean-Froidmentel'}
12: {key: '41275', libelle: 'La Ville-aux-Clercs'}
length: 13
[[Prototype]]: Array(0)

and the second console.log(ListVille) render []

The all with the error message :

Uncaught Error: Objects are not valid as a React child (found: object with keys {key, libelle}). 
If you meant to render a collection of children, use an array instead.

I tried :

  • put the fetch function in a UseEffect but it doesn't work neither
  • put a key in option like :
    <option key={item.key} value={item.key} > {item.libelle} </option>

Can someone help me or guide my to something ?

EDIT the seems to come from the ListVille const because when I tried this in mys render <div className='paragraphe'> Test {CP==='41160' ? ListVille[0].key : 'coucou'}</div> I've git the error message :

Uncaught TypeError: Cannot read properties of undefined (reading 'key')

EDIT 2 the problem seems to come from the fact that setList(response) doesn't set data in ListVille but I can't figure out why

EDIT 3 setList(response) does set data in ListVille but its's asynchronous so I need to force the setList to apply before doing anything else

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奈何桥上唱咆哮 2025-02-19 02:19:16

在您的代码中,我注意到以下行,我认为这会提供错误:

<div className='titre'> Saisissez votre ville {ListVille}</div>

Within your code I noticed the following line which I think provides the error:

<div className='titre'> Saisissez votre ville {ListVille}</div>
始终不够爱げ你 2025-02-19 02:19:16

经过大量的研究,我发现了问题所在,我在此处提出了一个更精确的问题,其他反应问题
问题解决了。
谢谢大家

After a lot of research I found where the problem was and I ask a more precise question about my problem in here other react question
And the probleme was solved.
Thanks everyone

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文