将setState设置为字符串而不是对象

时间:2017-07-18 09:33:18

标签: json api reactjs setstate

我正在尝试在加载网页时获取一个大的json文件,然后更新与该数据的反应状态。

目前,我有这段代码

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);
  });
}

代码将部分设置为sting,如屏幕截图所示,而不是实际的json对象。

react setstate problem

如何使用获取的json初始化状态。

1 个答案:

答案 0 :(得分:3)

首先,我建议使用fetch库而不是Promises和XMLHttpRequest。如果您需要支持IE 11及更低版本,可以使用polyfill

尽管您的代码仍然存在,但您似乎没有在JSON.parse上使用response,而是将您返回的JSON字符串转换为JavaScript对象。

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

虽然我觉得,fetch会更容易和更清洁,

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);
  });
}
相关问题