如何等待状态在 useEffect 之外更新

问题描述 投票:0回答:1

我正在尝试发布请求,然后接收其响应数据,然后发布其他请求:

const [groupId, setGroupId] = useState();

const handleFormSubmit = () => {
    e.preventDefault()
    axios.post('https://localhost:7028/group', someDemoData)
      .then((response) => {
        setGroupId(response.data)
      })
      .catch((error) => { console.log(error); })
    createParticipant(groupId);
}

所以我在这里尝试做的是使用 someDemoData 创建一个组,然后使用收到的响应数据设置 GroupId,然后将 groupId 传递给 createParticipant()。为了简单起见,目前 createParticipant 内部只有 console.log("groupId: " + groupId)。我得到的结果是未定义的。

我确实明白原因是当我调用 setGroupId 时,react 不会立即设置它,也不会等待它完成后再执行后续操作(异步),因此当调用 createParticipant(groupId) 时,groupId 尚未设置并且这就是为什么我的结果未定义。

我搜索了一些类似的问题,人们一直说使用 useEffect。但在这里我想等待它在我的handleFormSubmit()中更新,这样我就可以使用响应数据传递给createParticipant()。

那么如何等待groupId设置呢?

javascript reactjs react-hooks
1个回答
0
投票

groupId
永远不会改变(它不能,它是
const
),但你不需要它。将代码移至
.then
回调中并使用
response.data
:

axios
  .post("https://localhost:7028/group", someDemoData)
  .then((response) => {
    setGroupId(response.data);
    createParticipant(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
© www.soinside.com 2019 - 2024. All rights reserved.