React:如何遍历对象?

赤子56欢乐城

在此处输入图像描述

患者.用户返回在此处输入图像描述

patients.users 它是一个对象数组,但我无法循环遍历它。当我尝试调用patients.users[0] 时,它返回“TypeError:无法读取未定义的属性(读取'0')”。这是为什么?

function DoctorPanel() {
const location = useLocation();
const { id } = location.state;
const [patients, setPatiens] = useState('');

useEffect(() => {
  getPatients();
}, [])

const getPatients = () => {
  api.getDoctorById(id).then(response => {
    setPatiens(response.data)
})

 }

console.log(patients.users)



return (

<div>
    <div className="container">
      <h2 className="text-center">List of Patients</h2>
      <table className="table table-bordered table-striped">
          <thead>
              <th>Employee First Name</th>
              <th>Employee Last Name</th>
              <th>Number</th>
          </thead>
          <tbody>
            {
              patients.users.map(patient => 
                      <tr>
                          <td>{patient.firstName}</td>
                           <td>{patient.secondName}</td>
                           <td>{patient.number}</td>
                      </tr>
               )
            }
          </tbody>
      </table>    
  </div>
</div>

) }

for 循环、forEach 和 Object.keys 也不能正常工作。我如何遍历它并显示详细信息?

尼尔

问题是因为patients.users当你第一次渲染这个组件时数组中没有任何内容,所以它说无法读取未定义的属性,这是你的数组。

useEffect然后,您将在第一次渲染后运行的数据中获取数据。

您需要做的是您可以访问的任何地方patients.users更改为:

patient?.users或者patient && patient.users,这包括您的 console.log。这样做是在尝试访问数组之前检查patient数组是否未定义users

编辑:

useEffect将代码放在那里而不是调用外部存在的函数也是最佳实践。而且你在状态设置器setPatiens应该是一个错字setPatients

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章