在React中使用setState的多次提取请求

alb*_*ert 3 javascript fetch promise reactjs

我正在编写一个组件,它将对站点的两个不同路径进行提取请求,然后将其状态设置为生成的响应数据.我的代码看起来像这样:

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
        }));
    }
Run Code Online (Sandbox Code Playgroud)

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

iof*_*sli 15

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
        }));
    }
Run Code Online (Sandbox Code Playgroud)

如果你在then处理程序中返回Promise ,那么它将被解析为value.如果你返回任何其他东西(比如你的例子中的Array),它将按原样传递.所以你需要将你的promises数组包起来Promise.all使它成为Promise类型