反应setState设置为字符串而不是对象[英] react setState sets to string instead of object

本文是小编为大家收集整理的关于反应setState设置为字符串而不是对象的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

加载网页后,我正在尝试获取一个大JSON文件,然后使用该数据更新React状态.

目前,我有此代码

get(url) {
 return new Promise((resolve, reject) => {
   const req = new XMLHttpRequest();
   req.open('GET', url);
   req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
   req.onerror = (e) => reject(Error(`Network Error: ${e}`));
   req.send();
 });

}

componentDidMount(){
  this.get('https://x.com/data/tool.json').then((response) =>{
    this.setState({"sections" : response});
    console.log(this.state);
  }).catch((err) =>{
    console.log(err);
  });
}

代码将部分设置为刺激,如屏幕截图所示,而不是实际的JSON对象.

react setState问题

如何用获取的JSON初始化状态.

推荐答案

首先,我建议使用 fetch fetch 图书馆而不是承诺和xmlhttprequest.如果您需要支持IE 11及以下,则可以使用 polyfill

不过,坚持使用代码,您似乎在response上似乎都使用JSON.parse,要转动JSON字符串,您可以回到JavaScript对象.

this.setState({"sections" : JSON.parse(response)});

尽管我觉得,

,这将变得更容易,更干净
componentDidMount(){
  fetch('https://abx.com/data/tool.json').then(response =>{
    if (!response.ok) throw Error('Response not ok')

    return response.json(); // This is built in JSON.parse wrapped as a Promise
  }).then(json => {
    this.setState({"sections" : json});
  }).catch(err =>{
    console.log(err);
  });
}

本文地址:https://www.itbaoku.cn/post/1937786.html

问题描述

I am trying to fetch a big json file when the webpage has been loaded and then update react state with that data.

Currently, I have this code

get(url) {
 return new Promise((resolve, reject) => {
   const req = new XMLHttpRequest();
   req.open('GET', url);
   req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
   req.onerror = (e) => reject(Error(`Network Error: ${e}`));
   req.send();
 });

}

componentDidMount(){
  this.get('https://x.com/data/tool.json').then((response) =>{
    this.setState({"sections" : response});
    console.log(this.state);
  }).catch((err) =>{
    console.log(err);
  });
}

The code sets sections to a sting as shown in the screenshot instead of the actual json object.

react setstate problem

How can I initialize state with the fetched json.

推荐答案

Firstly I would recommend using the fetch library instead of Promises and XMLHttpRequest. If you need to support IE 11 and below, you can use a polyfill

Sticking with your code though, at no point do you appear to use JSON.parse on your response, to turn the JSON string you get back into a JavaScript object.

this.setState({"sections" : JSON.parse(response)});

This would be much easier and cleaner with fetch though I feel,

componentDidMount(){
  fetch('https://abx.com/data/tool.json').then(response =>{
    if (!response.ok) throw Error('Response not ok')

    return response.json(); // This is built in JSON.parse wrapped as a Promise
  }).then(json => {
    this.setState({"sections" : json});
  }).catch(err =>{
    console.log(err);
  });
}