首页 > 解决方案 > 如何通过 Promise 从两个 API 中设置数据?(反应.js)

问题描述

考虑下面的代码:

        componentDidMount(){
            const loginEmail = localStorage.getItem('loginEmail');
            const id = localStorage.getItem('id');

            Promise.all([
                fetch(`http://localhost:9000/api/users/view/${loginEmail}`)   // first API
                .then(value => 
                    value.json().then((res)=>{
                        this.setState({data: res.data});
                    })),
                fetch(`http://localhost:9000/api/event/view/${id}`)   // Second API
                .then(value => 
                    value.json().then((res)=>{
                        this.setState({data: res.data});
                    })),
                ])
                console.log(this.state.data)    // cant get the result
                .catch((err) => {
                    console.log(err);
                });
            }

这就是我从控制台得到的响应

在此处输入图像描述

那么我的做法是错误的吗?顺便说一句,我来自 JSON api 的数据是 Object 值。

标签: reactjsapipromisesetstate

解决方案


componentDidMount() {
 Promise.all([
   fetch(`http://localhost:9000/api/users/view/${loginEmail}`).then(blob => blob.json()),
   fetch(`http://localhost:9000/api/event/view/${id}`).then(blob => blob.json())
 ])
 .then([response1, response2] => {
   this.setState(prevState => {
    // do your operations
    return {
     ...prevState
    }
   })
 })
 .catch(error => {
  // handle error
 })
}

推荐阅读