【问题标题】:react setState sets to string instead of object反应 setState 设置为字符串而不是对象
【发布时间】:2017-12-23 02:08:12
【问题描述】:

我正在尝试在网页加载后获取一个大的 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);
  });
}

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

react setstate problem

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

【问题讨论】:

  • 你试过JSON.parse这个字符串吗?
  • 需要使用JSON.parse来解析字符串。
  • 我已经尝试了很多次。还首先尝试了 JSON.stringify 以确保一切顺利,但没有运气。

标签: json api reactjs setstate


【解决方案1】:

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

尽管坚持使用您的代码,但您似乎从未在您的 response 上使用 JSON.parse 来将您返回的 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);
  });
}

【讨论】:

  • 谢谢,这行得通。我重新安装了 babel-loader,之后您的代码运行良好。我不知道为什么 yarn 安装的二进制文件不能按预期工作。
猜你喜欢
  • 1970-01-01
  • 2018-07-19
  • 2018-04-22
  • 2018-03-18
  • 1970-01-01
  • 2011-08-06
  • 2014-02-08
  • 1970-01-01
  • 2013-02-23
相关资源
最近更新 更多