我很难弄清楚如何使用 React 和 TS 从 localStorage 设置组件状态。在我检查 localStorage 实例是否存在后,它仍然显示类型不兼容,因为localStorage.getItem()仍然可以返回字符串或 null。
如果我更改界面并添加,string |\xc2\xa0null我可以从 localStorage 设置状态,但是我无法再自行设置 localStorage,因为localStorage.setItem()似乎只接受string而不接受string | null
编辑
\n\n我想出了这个问题的“解决方案”。我不确定这是否是不好的做法,但它似乎有效。如果可以用更好的方式写出来,请告诉我。
\n\ncomponentWillMount() {\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)