简体   繁体   English

在异步 function 之前反应 usestate setvalue

[英]react usestate setvalue before async function

Trying out react context api for the first time.第一次尝试反应上下文 api。 Here is my react code using the context api这是我使用上下文 api 的反应代码

  const [valChanged, setValChanged] = useState(false);

  async function modalSave() {
    await setValChanged(true);// STEP 1
    await onEventSave();// This involves saving values to backend (async) STEP 2
  }

the onEventSave() async operation relies on valChanged value on previous step and therefore it has to be set to true before onEventSave is invoked. onEventSave() 异步操作依赖于上一步的 valChanged 值,因此必须在调用 onEventSave 之前将其设置为 true。 (step 1 has to be completed and its value set to true, before STEP 2 is invoked) (在调用 STEP 2 之前,必须完成步骤 1 并将其值设置为 true)

is there anything missing here?这里有什么遗漏吗?

If you are using hooks, there is no setState callback function, so you can do it with useEffect , like this:如果你使用钩子,没有setState回调 function,所以你可以用useEffect ,像这样:

useEffect(() => {
    onEventSave();
},[valChanged]);

The above function will be called whenever the valChanged is changed每当更改valChanged时,都会调用上述 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM