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

如何处理map方法中null引发的‘Cannot read properties of null’错误?

解决React列表遍历中null字段报错及条件渲染语法问题

问题说明

遍历JSON查询返回的peoplePosts字段时,部分条目里的featuredImage为null,直接访问post.featuredImage.node.sourceUrl会触发错误:Cannot read properties of null (reading 'node')。尝试在map方法内加入if判断处理空值,但因语法错误未成功。

原错误代码

{
  peoplePosts.map((post) => (
    <h2>{post.title}</h2>
    <p>{post.content}</p>
    <p>{post.featuredImage.node.sourceUrl}</p>
  ))
}

报错信息

"Cannot read properties of null (reading 'node')"

尝试的错误解决方案

{
  peoplePosts.map((post) => (
    <h2>{post.title}</h2>
    <p>{post.content}</p>
    if (post.featuredImage.node.sourceUrl == null) {
      <p>Ouch</p>
    } else {
      <p>Yay</p>
    }
  ))
}

报错信息

"Expected ")" but found "if""

正确解决方案

方案1:用可选链+三元表达式处理空值(保留所有条目)

{
  peoplePosts.map((post) => (
    <div key={post.id}> {/* React列表必须添加唯一key属性 */}
      <h2>{post.title}</h2>
      <p>{post.content}</p>
      {/* 用可选链?.避免访问null属性报错,三元表达式做条件渲染 */}
      {post.featuredImage?.node?.sourceUrl ? (
        <p>{post.featuredImage.node.sourceUrl}</p>
      ) : (
        <p>无封面图片</p>
      )}
    </div>
  ))
}
  • 核心说明:
    • ?.可选链操作符会在左侧值为null/undefined时直接返回undefined,避免抛出错误;
    • JSX中不能直接使用if语句,必须用三元表达式或逻辑运算符(如&&)这类表达式替代。

方案2:先过滤空值再遍历(只显示有有效封面的条目)

如果不需要展示没有封面图的帖子,可以先过滤掉无效条目:

{
  peoplePosts
    // 过滤出存在有效封面图的帖子
    .filter(post => post.featuredImage?.node?.sourceUrl)
    .map((post) => (
      <div key={post.id}>
        <h2>{post.title}</h2>
        <p>{post.content}</p>
        <p>{post.featuredImage.node.sourceUrl}</p>
      </div>
    ))
}

为什么你的尝试会报错?

在JSX的箭头函数返回内容中,直接写if语句属于语法错误——箭头函数用()包裹的是JSX元素集合,只能包含表达式,而if是语句,不能直接嵌入。必须用表达式形式的条件判断(如三元表达式)来替代。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:16:02