如何使用axios和React State Hook发出POST请求

编程入门 行业动态 更新时间:2024-10-27 15:21:27
本文介绍了如何使用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请求

本文发布于:2023-10-09 18:54:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   axios   React   POST   Hook

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!