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

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

反应设置状态问题

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

首先,我建议使用 fetch 库而不是 Promise 和 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);
});
}

最新更新