【问题标题】:Wait for State to update using UseState hook and then run code inside a funciton使用 UseState 钩子等待 State 更新,然后在函数内运行代码
【发布时间】:2020-12-16 18:36:49
【问题描述】:
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");
  };

当点击开始按钮时调用startlive函数...该函数用于更新状态,然后执行后面提到的代码。

但它在 setlivechartstate 甚至还没有完成更新时运行。

我不想使用使用效果挂钩,因为我只想在单击按钮时运行代码,因为它同时作为启动和停止工作,并且 liveActive 在其他功能中也发生了变化。所以使用 useEffect 和这种依赖产生了问题

我可以让这个函数工作的最好方法是什么,并且只在更新完成后运行代码

【问题讨论】:

    标签: javascript reactjs asynchronous callback use-state


    【解决方案1】:

    新设置的状态值将仅在下一次渲染时可用。我建议使用useeffect。或者您可以改用 useReducer。那也行

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2020-08-20
      • 2020-11-29
      • 2021-12-04
      • 1970-01-01
      • 2019-08-20
      • 2017-06-06
      • 2021-04-19
      • 2021-07-28
      相关资源
      最近更新 更多