简体   繁体   English

使用 UseState 钩子等待 State 更新,然后在函数中运行代码

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

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

/*- - - -after updation - - - >*/
    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");
  };

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我可以使此功能正常工作并且仅在更新完成后运行代码的最佳方法是什么

The new set state value will only be available on the next render.新设置的状态值仅在下一次渲染时可用。 I would suggest using useeffect.我建议使用useEffect。 Or you could use useReducer instead.或者你可以使用 useReducer 代替。 That would work too那也行

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

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