为了账号安全,请及时绑定邮箱和手机立即绑定

为什么在reactjs中使用JSON.parse会导致跨源错误?

为什么在reactjs中使用JSON.parse会导致跨源错误?

白猪掌柜的 2023-10-17 15:47:06
所以我有一个 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')) });但我知道数据可以被提取,因为 console.log(localStorage.getItem('user_data'));打印了这个 {"age":"20","gender":"male","goal":"recomp","height":"181","weight":" 80”}。所以我也尝试过,console.log(JSON.parse(this.state.healthData))但这会导致“跨源错误”事情是这段代码在我的 app.js 页面上运行,正如您可能在屏幕截图日志中看到的那样{age: "20", gender: "male", goal: "recomp", height: "181", weight: "80"}.那么是什么导致了这种情况,还有其他方法可以做到这一点吗?
查看完整描述

3 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

每当 JSON.parse() 收到无效字符串时,React 就会抛出跨域错误,您应该能够使用以下命令重新创建它JSON.parse('')。为什么 React 允许这种情况发生,我有自己的看法,但是您需要编写一些可以 JSON.parse() 的内容,以便localStorage.getItem('user_data')您的代码正常工作。您应该看到console.log(this.state.healthData)它不是有效的 JSON 字符串。



查看完整回答
反对 回复 2023-10-17
?
慕仙森

TA贡献1827条经验 获得超7个赞

我尝试这样做,效果很完美。


您必须确保状态已更改。(通过回调/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);

      }

    );

  };


查看完整回答
反对 回复 2023-10-17
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

所以我简单地通过在构造函数中设置状态而不是在组件 didMount 上设置状态来解决我的问题,但我不知道为什么当它的代码完全相同时它会起作用?


constructor(props) {

        super(props);

        this.state = {

            healthData: (JSON.parse(localStorage.getItem('user_data')))

        }

    } 


查看完整回答
反对 回复 2023-10-17
  • 3 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信