简体   繁体   中英

why does using JSON.parse cause a cross origin error in reactjs?

so I've got an array of JSON data saved to local storage like so

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

getting from local storage like this but a console.log(this.state.healthData) returns null

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

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

but I know the data can get pulled because a console.log(localStorage.getItem('user_data')); prints this {"age":"20","gender":"male","goal":"recomp","height":"181","weight":"80"}.

so I also tried console.log(JSON.parse(this.state.healthData)) but this causes a "cross origin error" 使用 JSON.phrase 后收到的错误

thing is this code works on my app.js page as you can probably see in the screenshot logging

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

so whats causing this and is there another way to do it?

I tried to do that, it works perfect.

You have to be sure that the state has been changed. (by callback/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);
      }
    );
  };

React throws a cross-origin error whenever JSON.parse() receives an invalid string, you should be able to recreate this with JSON.parse('') for example. Why React allows this to happen I have my own opinions on, but you'll need to write something that you can JSON.parse() to localStorage.getItem('user_data') for your code to work. You should see with console.log(this.state.healthData) that it's not a valid JSON string.

so I fixed my problem simply by setting the state in the constructor and not on component didMount but I have no idea why this works when its exactly the same code?

constructor(props) {
        super(props);
        this.state = {
            healthData: (JSON.parse(localStorage.getItem('user_data')))
        }
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM