如何存储和遍历 objects 的数组

how to store and iterate through array of objects

我无法从 object 访问该字段,因为它抛出以下错误:

TypeError: Cannot read property 'medicineId' of undefined when i try the peice of code below,

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

它给了我 index.js:1 警告:列表中的每个 child 都应该有一个唯一的“键”道具。 即使键是unique.but 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.

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

[] ? true: false; //true always

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

[].length ? true: false // false

所以用这个

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

您在 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])