【发布时间】: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;
}
我试图通过控制台记录目的地的状态,是的,它确实已更新。我做异步等待错了吗?谢谢你的帮助!
【问题讨论】:
-
你试过用 Promise 做吗? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
如果你使用
await,我不明白你为什么需要then。await应该解开then。
标签: javascript async-await axios