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

React应用使用localStorage getItem时出现JSON解析错误

问题解决:React登录组件localStorage解析JSON报错

错误原因

当localStorage.getItem("user")返回null(未找到对应存储条目)或undefined时,直接传给JSON.parse()会触发语法错误——JSON解析器无法处理这类非标准JSON格式的值。就算侥幸解析了null,后续访问null.name也会抛出"Cannot read properties of null"的错误。

修复方案

先对获取到的auth值做存在性校验,再进行解析和取值:

  1. 预处理用户数据:
const auth = localStorage.getItem("user");
// 仅当auth存在时解析,否则设为空对象兜底
const user = auth ? JSON.parse(auth) : {};
  1. 导航栏JSX中添加兜底逻辑:
<li>
  <Link onClick={logout} to="/signup">
    Logout ({user.name ?? 'Guest'})
  </Link>
</li>

也可以用更简洁的写法,直接在JSX中处理:

<li>
  <Link onClick={logout} to="/signup">
    Logout {auth ? `(${JSON.parse(auth)?.name ?? 'Guest'})` : ''}
  </Link>
</li>

额外提示

  • 登录成功时,务必确保用户信息是以JSON字符串格式存入localStorage:localStorage.setItem("user", JSON.stringify(userData))
  • 可以封装一个通用的localStorage操作工具函数,统一处理解析、校验逻辑,减少重复代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:42:04