本文介绍了如何使用axios和React State Hook发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何正确发出以下POST请求?
How can I properly make the following POST request?
const postWorkout = async () => {
setCompletedWorkout({
date: 31,
day: workout.mains[0].day,
exercises: completedExercises
})
try {
await axios.post('/history', completedWorkout)
} catch(error) {
throw error
}
}
我相信它会在完成workedout设置之前发出请求,如DB中的空文档所示:
I believe that it makes the request before completedWorkout is actually set as shown in the DB by an empty document:
推荐答案
我假设 setCompletedWorkout
将其设置为状态.如果是这样,您将需要等待完成,因为设置状态为异步.您可以这样使用 useEffect
来做到这一点:
I'm assuming setCompletedWorkout
is setting it to the state.If so, you will need to wait for that to be completed since setting a state is async.You can do this by using useEffect
like so:
useEffect(() => {
// POST HERE
}, [completedWorkout]);
设置您的 completedWorkout
后,将执行 useEffect
中的代码
The code inside useEffect
will execute once your completedWorkout
is set
这篇关于如何使用axios和React State Hook发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!