首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么不能在react钩子组件中设置间隔id?

为什么不能在react钩子组件中设置间隔id?
EN

Stack Overflow用户
提问于 2019-01-04 03:25:09
回答 1查看 164关注 0票数 0

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

DEMO ON CODESANDBOX

代码语言:javascript
复制
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?我遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-04 03:32:27

当你调用你的setState函数时,如果你想根据之前的状态更新状态,你必须传递一个函数,在你的例子中,这个函数应该叫做setTimer

代码语言:javascript
复制
setTimer(prevState => ({ ...prevState, seconds: updated }));

你的工作分支:https://codesandbox.io/s/244oozmr3p

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54028579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档