简体   繁体   English

使用 UseState hook 等待 State 更新,然后在函数内运行代码

[英]Wait for State to update using UseState hook and then run code inside a function

const startLive = () => {
    // connect to websocket only on start button
    
     setliveChartState({
      ...liveChartState,
      liveActive: !liveChartState.liveActive,
      historicLiveActive: true,
      start: new Date(),
    });

/*- - - -after updation this code needs to run - - - >*/
    const { ws, liveActive } = liveChartState;
    
    // if clicked on stop then close websocket
    if (!liveActive && ws) {
      ws.close();
    clearLiveInterval();
    }
    // if clicked on  start and websocket close then connect
    if ((!ws || ws.readyState === WebSocket.CLOSED)&& liveActive) connect();
    fetchData("historic");

/*----------*/
  };

I have a functional component我有一个功能组件

The startlive function gets called when start button is clicked... This function is used to update the state and then execute the code which comes later as mentioned. startlive 函数在单击开始按钮时被调用...该函数用于更新状态,然后执行后面提到的代码。

But it runs when setlivechartstate has not even completeted the updation.但是它在 setlivechartstate 甚至还没有完成更新时运行。

I do not want to use Use effect hook as i just want to run the code only when button is clicked as it is working both as start and stop and also liveActive is getting changed in other functions also.. So using useEffect with this dependency created problem我不想使用使用效果挂钩,因为我只想在单击按钮时运行代码,因为它同时作为开始和停止工作,而且 liveActive 在其他功能中也发生了变化..所以使用 useEffect 创建了这个依赖项问题

What is the best way i can make this function work and only run the code after the updation is done我可以使此功能正常工作并且仅在更新完成后运行代码的最佳方法是什么

It would be better if you use useEffect .如果您使用useEffect会更好。 and for your issue you can check inside useEffect that if button is clicked : true then only useEffect will execute your updation code.对于您的问题,您可以在useEffect内部检查是否clicked : true那么只有useEffect将执行您的更新代码。

useEffect(() => {
 if (ButtonClicked) {
   // do updation stuff
  }
}, [ButtonClicked]);

Considering your use case it would be great if you have a look at async/await functions and JavaScript Promises .考虑到您的用例,如果您查看 async/await 函数和JavaScript Promises会很棒。 In my opinion a good way to perform the update will be to maybe wrap your setliveChartState() function inside an async function, something like:在我看来,执行更新的一个好方法是将您的setliveChartState()函数包装在一个异步函数中,例如:

async function setLiveChart() {
   setliveChartState(...)
}

And then call your async setLiveChart() function inside your const startLive = () => {} like:然后在const startLive = () => {}调用async setLiveChart()函数,例如:

const startLive = () => {
    // connect to websocket only on start button
    
     setLiveChart().then(() => {

     /*- - - -after updation this code needs to run - - - >*/
    const { ws, liveActive } = liveChartState;
    
    // if clicked on stop then close websocket
    if (!liveActive && ws) {
      ws.close();
    clearLiveInterval();
    }

    // if clicked on  start and websocket close then connect
    if ((!ws || ws.readyState === WebSocket.CLOSED)&& liveActive) connect();
    fetchData("historic");

   /*----------*/
  }
};

You can also chain multiple then() callbacks like您还可以链接多个then()回调,例如

setLiveChart()
  .then(() => {})
  .then(() => {})
  .then...

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

相关问题 使用 UseState 钩子等待 State 更新,然后在函数中运行代码 - Wait for State to update using UseState hook and then run code inside a funciton 等待 state 更新 useState 钩子 - Wait for state update useState hook 如何使用 useState 钩子更新状态 - How to update state with the useState hook 如何在不使用 useState 挂钩重新渲染的情况下更新 state - How to update a state without re-rendering using useState hook 使用 useState Hook 引用函数状态时关闭 - Closure when reference to function state using useState Hook 调用 state 更新 function 在 state 更新 ZC1C425268E68384 组件4F 中使用功能状态钩子1 - Calling a state update function within a state update function - useState hook in React Functional component 如何在使用 UseState Hook 设置连续状态时等待 state - How to wait for state while setting consecutive states in react using UseState Hook 无法通过 function 调用使用 useState 挂钩设置 state - Unable to set state with useState hook with function call 使用 React 中的 useState 钩子将数组插入 state - Insert an array into state using useState hook in React React useState hook 似乎没有在显式调用 setter 函数时更新状态 - React useState hook does not seem to update the state on explicitly calling setter function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM