为什么不能在react hooks组件中设置间隔ID?

时间:2019-01-03 19:25:09

标签: javascript reactjs

它是带有alpha挂钩的react alpha版本。我正在尝试编写一个简单的计时器,但是某些方法无法正常工作。当我按停止键时,计时器ID仍然为空,即使应在按下启动键后对其进行更新。

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都为 null ?我想念什么?

1 个答案:

答案 0 :(得分:1)

当您调用自己的setState函数(在您的情况下应称为setTimer)时,如果要基于先前状态更新状态,则必须传递一个函数:

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

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