在React中使用setState的多次提取请求 [英] Multiple fetch requests with setState in React

查看:151
本文介绍了在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
        }));
    }

然而,当我去渲染我的两个州时,我发现它们是实际上仍然是空的,实际上还没有设置任何东西。我觉得我可能正在使用Promises或fetch()API错误,或者误解了setState的工作方式,或者是组合的东西。我测试了周围,发现在第一个then()之后,我的data1和data2仍然是Promises由于某种原因,并且还没有成为真正的JSON对象。无论哪种方式,我无法弄清楚我的生活在这里发生了什么。任何帮助或解释将不胜感激

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

如果您在中返回Promise,那么处理程序,然后它被解析为值。如果你返回任何其他东西(比如你的例子中的Array),它将按原样传递。因此,您需要将您的承诺数组包装到 Promise.all 以使其成为Promise类型

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

这篇关于在React中使用setState的多次提取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆