我正在尝试执行一些 get 和 post 请求,不知何故状态更新较晚(应该是 .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;
}
我尝试控制台记录目标状态,是的,它确实已更新。我做的异步等待错误吗?感谢您的帮助!
最佳答案
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);
}
如果您想在外部使用帖子(由您决定)。
关于javascript - React 中的 Axios 异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363571/