【问题标题】:Trying to access properties of an object nested in an array returns 'Cannot read properties of undefined', what can I change?尝试访问嵌套在数组中的对象的属性返回“无法读取未定义的属性”,我可以更改什么?
【发布时间】:2022-08-11 02:17:23
【问题描述】:

从“react”导入反应,{useEffect,useState}; 从\'./Representatives\'导入代表

导出默认函数 Searchbar() {

const [departement, setDepartement] = useState([]);
const [representative, setRepresentative] = useState([]);
const url = `https://geo.api.gouv.fr/departements?nom=${departement}&limit=1`;



useEffect(() => {
    const fetchGeoData = async () =>{
        const response = await fetch(url);

        const data = await response.json();
        console.log(data);

       if(data[0]) {
        setRepresentative(data)
       }
    }
    fetchGeoData();
}, [departement]);




return(
    <>
        <form departement={departement} setDepartement={setDepartement}>
            <input type=\'text\' placeholder=\"departement\" onChange={(event)=> setDepartement(event.target.value)} autoFocus ></input>
        </form>
        <Representatives  representative={representative} />
    </>
)

} 当我尝试从 api 显示数据时,出现此错误 \'Cannot read properties of undefined (reading \'nom\')\',我试图访问其他项目中嵌套数组的对象属性,但我总是遇到问题访问它。

import React from \"react\";

export default function Representatives(props){
    return(
        <>
            {props.representative.map(elu => 
                <h2>nome de l\'elu: {elu[0].nom}</h2>
                )
            }
        </>
    )
}

    标签: reactjs arrays api react-hooks fetch


    【解决方案1】:

    因为你不需要在{elu之后使用[0],所以从api返回的elu对象不是数组式的。

    那是你的props.representative

    [
        {
            "nom": "Territoire de Belfort",
            "code": "90",
            "codeRegion": "27",
            "_score": 0.3556145506116622
        }
    ]
    

    这就是 .map, elu 对象的结果

    {
      "nom": "Territoire de Belfort",
      "code": "90",
      "codeRegion": "27",
      "_score": 0.3556145506116622
    }
    

    所以它会是(假设code 是唯一的,需要key 属性)

    function Representatives(props) {
      return (
        <>
          {props.representative.map((elu) => (
            <h2 key={elu.code}>nome de l'elu: {elu.nom}</h2>
          ))}
        </>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2023-03-20
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多