小编jet*_*318的帖子

如何从 localStorage 设置 React 状态?

我很难弄清楚如何使用 React 和 TS 从 localStorage 设置组件状态。在我检查 localStorage 实例是否存在后,它仍然显示类型不兼容,因为localStorage.getItem()仍然可以返回字符串或 null。

\n\n

如果我更改界面并添加,string |\xc2\xa0null我可以从 localStorage 设置状态,但是我无法再自行设置 localStorage,因为localStorage.setItem()似乎只接受string而不接受string | null

\n\n

编辑

\n\n

我想出了这个问题的“解决方案”。我不确定这是否是不好的做法,但它似乎有效。如果可以用更好的方式写出来,请告诉我。

\n\n
componentWillMount() {\n    let from = localStorage.getItem(\'from\');\n    let to = localStorage.getItem(\'to\');\n    let fromId = localStorage.getItem(\'fromId\');\n    let toId = localStorage.getItem(\'toId\');\n\n    if (typeof from === \'string\' &&\n        typeof to === \'string\' &&\n        typeof fromId === \'string\' &&\n        typeof toId === \'string\') {\n\n      this.setState({\n        inputFrom: from,\n        inputTo: to,\n        fromId: fromId,\n        toId: toId,\n …
Run Code Online (Sandbox Code Playgroud)

local-storage typescript reactjs

5
推荐指数
1
解决办法
3361
查看次数

标签 统计

local-storage ×1

reactjs ×1

typescript ×1