【问题标题】:how to store and iterate through array of objects如何存储和遍历对象数组
【发布时间】:2021-05-26 04:29:55
【问题描述】:

我无法从对象访问该字段,因为它会引发以下错误:

TypeError:无法读取未定义的属性“medicineId” 当我尝试下面的代码时,

{medlist &&
  medlist.map(({medicineId, medicineName }) => (
    <li  key={medicineId} >
      <h1>{medicineName}</h1>
    </li>               
  ))
}

它给了我 index.js:1 警告:列表中的每个孩子都应该有一个唯一的“键”道具。即使键是唯一的。但是 idk 它给了我这个唯一的键道具错误因为它是字符串类型。

注意medicineId 是字符串类型。我试图通过将那段代码更改为来克服这个问题,

{medlist &&
  medlist.map((med,idx) => (
    <li  key={idx} >
      <h1>{med.medicineName}</h1>
    </li>               
  ))
}

现在我没有收到唯一键的警告,但是没有显示标签 med.medicineName 当我尝试 {console.log(med.medicineName)} 它是未定义

const fetchMedicineList = () =>{
  return axios.get('http://localhost:8080/medicine')
    .then(({data})=>{
      console.log(data[0].medicineName)//this prints the medicine name.
      return data;
    })
    .catch(err =>{
      console.error(err)
    });
}
but when i tried to store the object array inside usestate,
  const [medlist, setMedlist] = useState([])or**useState([{}])**
 useEffect(() => {
        fetchMedicineList().then(medicineList=>{
            setMedlist([...medlist,medicineList]);
            
        })
        
    }, [medlist])
and i cant print or access medlist[0].medicineName ,it says **undefine** what am i doing wrong here, thanks.

【问题讨论】:

    标签: javascript reactjs undefined


    【解决方案1】:

    这只是检查数组是否存在。所以这永远是真的。

    [] ? true: false; //true always
    

    所以你必须像这样检查它的长度

    [].length ? true: false // false
    

    所以用这个

    {medlist.length &&
      medlist.map(({medicineId, medicineName }) => (
        <li  key={medicineId} >
          <h1>{medicineName}</h1>
        </li>               
      ))
    }
    

    【讨论】:

      【解决方案2】:

      您在 setMedlist useState 中设置了没有展开操作的 API 响应。

      检查一下

      const initailValue =[];
      const apiResponse =[{
      'medicineName':'abc'
      }]
      const neWArr = [...initailValue,...apiResponse]
      console.log(neWArr[0].medicineName)
      

      为你的问题试试这个,

        const [medlist, setMedlist] = useState([])
        useEffect(() => {
          fetchMedicineList().then(medicineList=>{
              setMedlist([...medlist,...medicineList]);
              
          })
          
      }, [medlist])
      

      【讨论】:

        猜你喜欢
        • 2021-06-18
        • 2019-07-28
        • 2022-11-17
        • 2023-03-22
        • 1970-01-01
        • 2015-07-10
        • 2017-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多