【问题标题】:How to setState the data from two API by Promise? (React.js) [duplicate]如何通过 Promise 从两个 API 中设置数据? (React.js)[重复]
【发布时间】:2020-06-12 16:04:55
【问题描述】:

考虑下面的代码:

        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 值。

【问题讨论】:

标签: reactjs api promise setstate


【解决方案1】:
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
 })
}

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2019-05-01
    • 2017-11-10
    • 2018-10-29
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多