首页 > 解决方案 > React 迭代嵌套数组给出错误无法读取 null 的属性(读取“值”)

问题描述

尝试映射嵌套数组时出现错误:数据结构如下:

错误:无法读取 null 的属性(读取“值”)

export const testData = [
  {
    "date": [
      "2016-09-0912:00:00",
      "2015-09-0913:10:00"
    ],
    "title": [
      {
        "name": 'Name 1',
        "description": [
          {
            "value": 7898
          },
          {
            "value": 7898
          }
        ]
      },
      {
        "name": 'Name 2',
        "description": [
          {
            "value": 3244
          },
          {
            "value": 4343
          }
        ]
      },
      {
        "name": 'Name 3',
        "description": [
          null,
          null
        ]
      }
    ]
  }
]

我努力了:

 <div style={{ color: 'white' }}>
    Hello
    {testData.map(inner => {
      return (
        <p style={{color: 'white'}}>{inner.title.map(inside => {
          return (
          inside.description.map(point => {
            return (
              point.value
            )
          })
          )
        })}</p>
      )
    })}
  </div>

所以有点迷茫?

标签: arraysreactjsiteration

解决方案


这是因为该对象的值为 null Name 3。一个快速的解决方法是使用可选链接。

前任

 <div style={{ color: 'white' }}>
    Hello
    {testData.map(inner => {
      return (
        <p style={{color: 'white'}}>{inner.title.map(inside => {
          return (
          inside.description.map(point => {
            return (
              point?.value // here
            )
          })
          )
        })}</p>
      )
    })}
  </div>

密码箱


推荐阅读