![](/img/trans.png)
[英]How to make one state change only after other state has been changed in functional component?
[英]React change state automatically after a post has been added on other component
那么問題是你沒有等待 axios 調用完成,因為 axios.post 方法是異步的。 您需要使 function 異步並等待 axios.post 方法,這里是一個如何執行此操作的示例。
const createTicket = async (e) => {
e.preventDefault();
try {
await axios.post(postTicketURL, {
userID: userID,
content: ticketArea
}, configHeader);
await reloadTickets();
}
catch (error) {
console.log(error);
}
}
更新:我看到你已經在你的父組件中使用了.then 和.catch 方法,所以你可以這樣解決這個問題:
const createTicket = async (e: any) => {
e.preventDefault();
axios.post(postTicketURL, {
userID: userID,
content: ticketArea
}, configHeader).then((res: any) => {
console.log(res);
reloadTickets();
}).catch((err: any) => {
console.log(err);
});
}
但我會推薦 async await 方法,而且你應該在 TicketsComponent -> fetchTickets 中重構你的代碼以匹配它。 為什么? 因為 async await 是一種更加清晰和現代的方法,並且您正在避免潛在的回調地獄,例如,如果您現在想要等待 reloadTickets function 正確結束。 您可以在此處找到有關此主題的更多信息: https://www.loginradius.com/blog/async/callback-vs-promises-vs-async-await/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.