【发布时间】:2018-09-20 02:39:45
【问题描述】:
我正在编写一个组件,它将向站点的两个不同路径发出获取请求,然后将其状态设置为生成的响应数据。我的代码如下所示:
export default class TestBeta extends React.Component {
constructor(props){
super(props);
this.state = {
recentInfo: [],
allTimeInfo: []
};
}
componentDidMount(){
Promise.all([
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent'),
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
])
.then(([res1, res2]) => [res1.json(), res2.json()])
.then(([data1, data2]) => this.setState({
recentInfo: data1,
alltimeInfo: data2
}));
}
但是,当我去渲染我的两个状态时,我发现它们实际上仍然是空的,实际上还没有设置任何东西。我觉得我可能错误地使用了 Promises 或 fetch() API,或者误解了 setState 的工作原理,或者是两者兼而有之。我测试了一下,发现在第一个 then() 之后,我的 data1 和 data2 由于某种原因仍然是 Promise,还没有成为真正的 JSON 对象。无论哪种方式,我都无法弄清楚这里发生了什么。任何帮助或解释将不胜感激
【问题讨论】:
-
你需要在 res.json() 上做一个 Promise.all 并且它也会返回一个 Promise。目前你的第二个 then() 块永远不会被处理
-
所以会是这样:Promise.all([...]).then(Promise.all([res1, res2] => ...).then(Promise.all([data1 , data2]) => ...)?
-
是
Promise.all([res1.json(), res2.json()])
标签: javascript reactjs promise fetch