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

React fetch请求API渲染时报Cannot read properties of null如何解决

解决方案

你遇到的报错本质是访问null/undefined类型值的属性导致的,可通过以下两种方案实现默认值兜底:

方案1:可选链 + 空值合并运算符(推荐,ES2020+支持)

这是最简洁的写法,只会在属性链路中断或最终值为null/undefined时返回默认值,不会误覆盖空字符串、0等合法有效值:
将对应代码行替换为:

{character?.owner?.user?.username ?? 'No User'}

修改后的完整对应片段:

<Typography color="textSecondary" variant="subtitle2">
  {character?.owner?.user?.username ?? 'No User'}
</Typography>

方案2:兼容旧环境的逻辑判断写法

如果你的项目不支持ES2020新语法,可以用层级判断+逻辑或实现兜底,注意该写法会把空字符串、0等假值也替换为默认值:
将对应代码行替换为:

{(character && character.owner && character.owner.user && character.owner.user.username) || 'No User'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:54:01