未捕获类型错误:无法读取 ./src/requestMethods.js 处的 null 属性(读取“accessToken”)

问题描述 投票:0回答:1

我正在尝试从 localStorage

accessToken
中获取
persist:root
值,但最初的值为空,并且某些属性甚至没有添加,我正在尝试访问它。 我想忽略

的空值
const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user).currentUser.accessToken;

哪里

Key = persist:root Value = {"user":"{\"currentUser\":null,\"isFetching\":false,\"error\":false}","_persist":"{\"version\":1,\"rehydrated\":true}"}

但是当我删除 localStorage

persist:root
然后, 我尝试使用

const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user)?.currentUser?.accessToken;

以各种可能的方式。但因为

?.
操作员
JSON.parse()
没有得到它,
因此需要找到其他可能的方法来在使用
JSON.parse()
方法解析时面对 null 值,以及当首先 localStorage 为空时该怎么做。

  • 我做不到
    const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user)?.currentUser?.accessToken || "";

(错误):未捕获类型错误:无法读取 null 的属性(读取“用户”) 在./src/requestMethods.js (requestMethods.js:4:1)

reactjs json local-storage token redux-persist
1个回答
0
投票

我在 currentUser 中看不到 accessToken。

尝试

console.log(JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user).currentUser) 

如果值正确,则调试每个深度

© www.soinside.com 2019 - 2024. All rights reserved.