【问题标题】:Trying to display key of object in array to table试图将数组中对象的键显示到表中
【发布时间】:2019-12-02 17:01:42
【问题描述】:

这感觉像是一个超级简单的问题,我以为我知道解决方案,但就是不知道为什么它不起作用。

我正在尝试在表格中显示 Firestore 中的记录。 一些字段可以很好地进入表中,但其中一个字段由 对象数组给我带来了问题,该对象包含 childName、childAge 和 childId。我正在尝试显示 childName。

我只想显示第一个 Children 对象的子名称。

但我不断收到错误消息:

“TypeError: 无法读取未定义的属性‘0’”

<TableBody>
        {forms.map(row => (
          <TableRow key={row.id}>

             //the TableCell below where I am trying to display childName
            <TableCell component={"th"} scope={"row"}>
              {row.children[0].childName}
            </TableCell>

            <TableCell>{row.timeIn}</TableCell>
            <TableCell>{row.timeOut}</TableCell>
            <TableCell>{row.parentName}</TableCell>
            <TableCell>{row.shoeBoxNumber}</TableCell>
          </TableRow>
        ))}
      </TableBody>

以下是完整的错误截图:

下面是我的状态,我正在使用 React 钩子:

【问题讨论】:

  • 你想只显示第一个对象
  • 你可以遍历它。意思是无法读取 undefined 的属性 '0' is row.children[0] in undefined 添加检查以检查其值
  • 是的,只是 Children 的第一个对象。我会更新我的问题

标签: javascript arrays json reactjs object


【解决方案1】:

尝试添加验证:如果数组不为空: {row.children && row.children.length && row.children[0].childName}

<TableBody>
        {forms.map(row => (
          <TableRow key={row.id}>

             //the TableCell below where I am trying to display childName
            <TableCell component={"th"} scope={"row"}>
              {row.children && row.children.length && row.children[0].childName}
            </TableCell>

            <TableCell>{row.timeIn}</TableCell>
            <TableCell>{row.timeOut}</TableCell>
            <TableCell>{row.parentName}</TableCell>
            <TableCell>{row.shoeBoxNumber}</TableCell>
          </TableRow>
        ))}
      </TableBody>

【讨论】:

  • 是的,成功了。我曾考虑过进行验证,认为数据可能尚未到达,这会给我一个空数组,但随后看到其他数据正在显示,所以我认为这不是问题,这正是我尝试的方式访问数据。非常感谢
【解决方案2】:

您可以添加验证以检查您的数组是否存在数据

<TableBody>
        {forms.map((row)=> (
          <TableRow key={row.id}>

             //the TableCell below where I am trying to display childName
           if(row.children[0]){
             return (
              <TableCell component={"th"} scope={"row"}>
              {row.children[0].childName}
              </TableCell>
              )
            }

            <TableCell>{row.timeIn}</TableCell>
            <TableCell>{row.timeOut}</TableCell>
            <TableCell>{row.parentName}</TableCell>
            <TableCell>{row.shoeBoxNumber}</TableCell>
          </TableRow>
        ))}
      </TableBody>

【讨论】:

  • 没有解释的代码很少被赞成。此外,您已将第一个元素中显示的数据从第一个孩子的 childName 更改为当前孩子的 childName。这可能也需要一些解释......
猜你喜欢
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2021-12-04
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
相关资源
最近更新 更多