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

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

本文介绍了将setState设置为字符串而不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当前,我有此代码

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对象.

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

反应设置状态问题

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

How can I initialize state with the fetched json.

推荐答案

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

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

尽管如此,但在任何情况下,您似乎都不会在response上使用JSON.parse来将返回的JSON字符串转换为JavaScript对象.

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

尽管我觉得,使用fetch会更轻松,更干净

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

这篇关于将setState设置为字符串而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:22