You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React遍历嵌套数组报错Cannot read properties of null (reading 'value')怎么解决

报错原因

你使用的testData数据中,name为Name 3的对象下description数组的两个元素均为null,遍历到该部分数据时直接访问point.value会触发空属性读取报错。

解决方案

以下两种方案均可修复问题,同时补充了React列表渲染必填的key属性,避免控制台警告:

方案1:可选链+空值合并(推荐)

适配绝大多数现代React项目,写法简洁,可自定义空值展示内容:

<div style={{ color: 'white' }}>
  Hello
  {testData.map((inner, idx) => (
    <p key={idx} style={{color: 'white'}}>
      {inner.title.map((inside, titleIdx) => (
        inside.description.map((point, descIdx) => point?.value ?? '-')
      ))}
    </p>
  ))}
</div>

示例中空值默认显示-,可根据业务需求自行修改为0或者空字符串等内容。

方案2:条件判断兼容

适用于不支持ES2020新特性的老旧项目,手动判断空值:

inside.description.map((point, descIdx) => {
  if (point !== null && point.hasOwnProperty('value')) {
    return point.value
  }
  return '-'
})

内容的提问来源于stack exchange,提问作者Sole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:30:00