开发者问题收集

React 中的 Axios Async-Await

2019-05-29
2965

我尝试执行一些获取和发布请求,不知何故状态更新较晚(应该是 .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;
}

我尝试在控制台记录目的地的状态,是的,它确实已更新。我是否错误地执行了异步等待?感谢您的帮助!

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);
}

如果您想在外面使用岗位,这取决于您。

Garry
2019-05-29