react处理多次请求_在React中使用setState的多次提取请求

I'm writing a component that will make fetch requests to two different paths of a site, then set its states to the resulting response data. My code looks something like this:

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

}));

}

However, when I go to render my two states, I find that they are actually still empty, and in fact have not been set to anything. I feel like I might be using either the Promises or fetch() API wrong, or misunderstanding how setState works, or a combination of things. I tested around and found that after the first then(), my data1 and data2 were still Promises for some reason, and had not become actual JSON objects yet. Either way, I cannot figure out for the life of me what's going on here. Any help or explanation would be appreciated

解决方案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]) => Promise.all([res1.json(), res2.json()]))

.then(([data1, data2]) => this.setState({

recentInfo: data1,

alltimeInfo: data2

}));

}

If you return Promise in then handler, then it's resolved to value. If you return anything else (like Array in your example), it will be passed as is. So you need to wrap your array of promises to Promise.all to make it Promise type

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值