在 React 中使用 setState 的多个获取请求

Multiple fetch requests with setState in React(在 React 中使用 setState 的多个获取请求)

本文介绍了在 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 出于某种原因仍然是 Promise,还没有成为真正的 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
        }));
    }

如果您在 then 处理程序中返回 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 的多个获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 React 中使用 setState 的多个获取请求

基础教程推荐