【问题标题】:Axios Async-Await in ReactReact 中的 Axios 异步等待
【发布时间】:2019-05-29 23:09:56
【问题描述】:

我正在尝试做一些获取和发布请求,不知何故状态更新较晚(应该是 .get,然后是 .post)

async componentDidMount() {

    const {destination, weight} = this.state;


    axios.get(`https://myapi`)
        .then(res => {
            const customer = res.data;

            this.setState({ customer,
                destination: customer[0].address[0].city,
            }
        })

   axios.post(`https://myapi`, {destination, weight})
        .then((post)=>{
          const delivery = post.data;
            this.setState({ delivery,
              cost: delivery[0].cost[0].value
             });
        });

        return post;
}

状态已更新,但不知何故,帖子出现了应该填写目的地的错误。我发现解决方案是使用异步等待。我尝试实现它,但它不起作用。

这是我尝试过的

async componentDidMount() {

        const {destination, weight} = this.state;


        axios.get(`https://myapi`)
            .then(res => {
                const customer = res.data;

                this.setState({ customer,
                    destination: customer[0].address[0].city,
                }
            })

const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
            .then((post)=>{
          console.log(this.state.destination);
              const delivery = post.data;
                this.setState({ delivery,
                  cost: delivery[0].cost[0].value
                 });
            });

            return post;
}

我试图通过控制台记录目的地的状态,是的,它确实已更新。我做异步等待错了吗?谢谢你的帮助!

【问题讨论】:

标签: javascript async-await axios


【解决方案1】:
try{
   let res = await axios.get(`https://myapi`);
   if (res) {
     const customer = res.data;
     this.setState({ customer,
        destination: customer[0].address[0].city,
     });
     const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
     if (postRes) {
       const delivery = post.data;
         this.setState({ delivery,
           cost: delivery[0].cost[0].value
         });
     }
   }
}catch (err) {
  console.log(err);
}

如果你想在外面使用帖子,这取决于你。

【讨论】:

  • 为什么如果(res)?您应该将 async 添加到此块中,否则 await 将无法解决问题
  • 是的,必须在函数定义中添加异步,我认为这不是问题。关于 if(res),get 可能会返回包含 " " 或 null 的空响应,因此在这种情况下您不要设置状态。
  • 当我将 POST 放在 if 之外时,它工作得很好。非常感谢!!!!
  • 当我将 POST 放在 if 之外时,它工作得很好。非常感谢!!!!
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 2019-03-17
  • 2020-12-09
  • 2018-12-09
  • 2021-08-25
  • 1970-01-01
  • 2018-02-15
  • 2021-04-13
相关资源
最近更新 更多