【问题标题】:react hook conditional useState - JSON.parse(...) is null反应钩子条件 useState - JSON.parse(...) 为空
【发布时间】:2021-07-13 23:20:24
【问题描述】:

我正在使用 react hook,如果存在,我想从客户端的本地存储中检索一些信息。

下面是我定义的应用状态:

const [name, setName] = useState(JSON.parse(localStorage.getItem("personalInfo")).name || "");

我希望如果本地存储中没有数据,那么将使用空字符串作为初始状态。

但是,它会产生错误:TypeError: JSON.parse(...) is null

说明即使本地存储为空,空字符串仍然不能作为初始状态。

它之前按预期工作,但是在我在另一个组件中添加一些复杂的代码之后,它开始产生错误。知道为什么会发生这种情况,以便我知道在哪里调试吗?

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    你可以使用

    const localStore = localStorage.getItem("personalInfo")
    const [name, setName] = useState(localStore ? JSON.parse(localStore).name : "");
    

    或者你可以安全地解析 JSON

    function parseJson(){
        try {
          return JSON.parse(localStorage.getItem("personalInfo")).name;
        } catch(ex){
          return "";
        }
    }
    
    const [name, setName] = useState(parseJson();
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多