首页 > 解决方案 > 为什么在 reactjs 中使用 JSON.parse 会导致跨源错误?

问题描述

所以我有一个 JSON 数据数组保存到本地存储,就像这样

localStorage.setItem('user_data', JSON.stringify(data));

像这样从本地存储中获取,但是 console.log(this.state.healthData) 返回 null

  constructor(props) {
        super(props);
        this.state = {
            healthData: {}
        }
    }

 this.setState({ healthData: JSON.parse(localStorage.getItem('user_data')) });

但我知道数据可能会被提取,因为 a console.log(localStorage.getItem('user_data'));打印出这个 {"age":"20","gender":"male","goal":"recomp","height":"181","weight":" 80"}。

所以我也尝试过console.log(JSON.parse(this.state.healthData)),但这会导致“跨源错误” 使用 JSON.phrase 后收到的错误

问题是此代码适用于我的 app.js 页面,正如您可能在屏幕截图日志中看到的那样

{age: "20", gender: "male", goal: "recomp", height: "181", weight: "80"}.

那么是什么原因造成的,还有其他方法吗?

标签: javascripthtmljsonreactjs

解决方案


我试着这样做,它完美无缺。

您必须确保状态已更改。(通过回调/useEffect)

test = () => {
    const data = {
      age: "20",
      gender: "male",
      goal: "recomp",
      height: "181",
      weight: "80"
    };
    localStorage.setItem("user_data", JSON.stringify(data));
    this.setState(
      {
        healthData: JSON.parse(localStorage.getItem("user_data"))
      },
      () => {
        console.log(this.state.healthData);
      }
    );
  };

推荐阅读