【发布时间】: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