反应useState不更新值

时间:2020-07-08 08:21:57

标签: reactjs typescript react-hooks state react-state

我正在使用React Typescript,我已经使用useState来更新值,但是该值未在函数中更新,我已经使用过const [isGameStarted, setIsGameStarted] = React.useState<any>('0');,并且正在更新{ {1}}函数,

useEffect()

在这里,我将其值更新为1,但是对于我的React.useEffect(() => { if(gameData?.game?.roundStarted) { if(isGameStarted == '0') { console.log("round is started"); setIsGameStarted('1'); } } }, [gameData]); 函数而言,它并没有更新该值,在这里我提到了interval函数,该间隔函数每1秒调用一次,但是总是将interval的值视为0,有人可以帮我为什么即使在isGameStarted函数调用之后它仍未将值变为1,我们将不胜感激

useEffect()

完整代码:

const interval = () => {
        let timer = setSeconds, minutes, seconds;
        
        console.log("isGameStarted : "+isGameStarted);

        if(isGameStarted == '0') {
            alert("0")
        } else {
            alert("1")
        }
    }   

2 个答案:

答案 0 :(得分:2)

如果您确定每次GameData更新时页面都会呈现,则可以执行此操作。

React.useEffect(() => {
    if(gameData?.game?.roundStarted) {
        if(isGameStarted == '0') {
            console.log("round is started");
            setIsGameStarted('1');
        }
    }
}, [gameData?.game?.roundStarted]);

useEffect不会遍历对象中的所有道具,因此您必须将确切的值明确地放在监视列表中。

答案 1 :(得分:2)

在传递给setInterval的函数中,有一堆stale closures,这是一个工作计时器的示例:

const App = () => {
  const [
    stateInInterval,
    setStateInInterval,
  ] = React.useState({
    count: 0,
    running: false,
  });

  const interval = () => {
    setStateInInterval((current) => {
      if (!current.running) {
        clearInterval(current.interval);
        return current;
      }
      if (current.count > 9) {
        return { ...current, running: false };
      }
      return {
        ...current,
        count: current.count + 1,
      };
    });
  };

  const startTimer = () => {
    if (stateInInterval.running) {
      //already running
      return;
    }
    setStateInInterval((current) => ({
      ...current,
      interval: setInterval(interval, 1000),
      running: true,
    }));
  };
  const stopTimer = () => {
    setStateInInterval((current) => ({
      ...current,
      running: false,
    }));
  };
  const resetTimer = () => {
    setStateInInterval((current) => ({
      ...current,
      count: 0,
    }));
  };

  return (
    <div>
      <button onClick={startTimer}>start timer</button>
      <button onClick={stopTimer}>stop timer</button>
      <button onClick={resetTimer}>reset timer</button>
      <h4>{stateInInterval.count}</h4>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>