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
相关产品推荐
相关产品推荐

