javascript - 为什么无法在 React hooks 组件中设置间隔 id?

标签 javascript reactjs

它是 React alpha 版本,其中有钩子(Hook)。我正在尝试编写一个简单的计时器,但有些东西无法正常工作。当我按下停止键时,计时器 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?我错过了什么?

最佳答案

当您调用 setState 函数(在您的情况下应称为 setTimer)时,如果您想根据状态更新状态,则必须传递一个函数之前的状态:

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

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

关于javascript - 为什么无法在 React hooks 组件中设置间隔 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54028579/

相关文章:

reactjs - 基于 React 的 SPA 中的 SEO

javascript - 指定我要包含的 ClojureScript 文件

webview - 使用 Appium 访问 React 元素以实现自动化

javascript - React.js 中的初始化器?

reactjs - 错误 : idpiframe_initialization_failed while implementing OAuth 2. 0

javascript - 为什么 setState 返回未定义?

javascript - 如何使用 Javascript 根据先前的下拉值显示第二个下拉列表

javascript - 表格标签内的 HTML 标题标签的浏览器问题

javascript - setInterval() 对性能不利吗?

javascript - 光线转换使敌人跳跃