代码之家  ›  专栏  ›  技术社区  ›  Javid Asgarov

为什么不能在React Hooks组件中设置间隔ID?

  •  0
  • Javid Asgarov  · 技术社区  · 6 年前

    它是React Alpha版本,里面有钩子。我正试图编写一个简单的计时器,但有些东西不能正常工作。当我按下Stop时,计时器ID仍然为空,即使它应该在按下Start之后更新。

    DEMO ON CODESANDBOX

    function Timer() {
      const [timer, setTimer] = useState({
        id: null,
        seconds: 0,
        started: new Date().getTime()
      });
    
      let timerId = null;
    
      const incrementSeconds = () => {
        const now = new Date().getTime();
        const updated = parseInt((now - timer.started) / 1000, 10);
        setTimer({ ...timer, seconds: updated });
      };
    
      const start = () => {
        const myId = setInterval(incrementSeconds, 1000);
        timerId = myId;
        console.log(timerId);
        setTimer({
          id: myId,
          seconds: 0,
          started: new Date().getTime()
        });
      };
    
      const stop = () => {
        // for some reason both timer and timerId are null
        console.log(timer, timerId);
        clearInterval(timer.id);
        setTimer({ ...timer, seconds: 0 });
      };
    
      return (
        <div>
          <button onClick={start}>Start!</button>
          <button onClick={stop}>Stop</button>
          <h2>Seconds: {timer.seconds}</h2>
        </div>
      );
    }
    

    问题是,为什么timerid在变量和状态中都是 无效的 ?我错过了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   quirimmo    6 年前

    当你打电话给你 setState 函数,应调用 setTimer 在您的情况下,如果要基于以前的状态更新状态,则必须传递函数:

    setTimer(prevState => ({ ...prevState, seconds: updated }));
    

    您的工作叉: https://codesandbox.io/s/244oozmr3p