Javascript 如何存储和遍历对象数组
我无法从对象访问字段,因为它引发以下错误: TypeError:无法读取未定义的属性“medicineId” 当我尝试下面的代码时, 现在我没有收到unique key的警告,但是没有显示标签med.medicineName。 当我尝试{console.log(med.medicineName)} 它是未定义的Javascript 如何存储和遍历对象数组,javascript,reactjs,undefined,Javascript,Reactjs,Undefined,我无法从对象访问字段,因为它引发以下错误: TypeError:无法读取未定义的属性“medicineId” 当我尝试下面的代码时, 现在我没有收到unique key的警告,但是没有显示标签med.medicineName。 当我尝试{console.log(med.medicineName)} 它是未定义的 const fetchMedicineList = () =>{ return axios.get('http://localhost:8080/medicine')
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.
这只是检查数组是否存在。所以这永远是真的
[] ? true: false; //true always
所以你必须像这样检查它的长度
[].length ? true: false // false
所以用这个
{medlist.length &&
medlist.map(({medicineId, medicineName }) => (
<li key={medicineId} >
<h1>{medicineName}</h1>
</li>
))
}
{medlist.length&&
medlist.map({medicineId,medicineName})=>(
{medicineName}
))
}
在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])
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])