Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 停止正在使用的计时器_Reactjs - Fatal编程技术网

Reactjs 停止正在使用的计时器

Reactjs 停止正在使用的计时器,reactjs,Reactjs,据我所知,计时器是在不同的范围内调用的。。如何完成停止计时器的功能?这里有点疯狂,谢谢你的帮助 const SomeComponent = ({ isPlaying }) => { let timer = null; React.useEffect(() => { if (isPlaying) { startTimer(); } },[isPlaying]); const startTimer = () => { time

据我所知,计时器是在不同的范围内调用的。。如何完成停止计时器的功能?这里有点疯狂,谢谢你的帮助

const SomeComponent = ({ isPlaying }) => {
  let timer = null;

  React.useEffect(() => {
    if (isPlaying) {
      startTimer();
    }
  },[isPlaying]);

  const startTimer = () => {
    timer = setInterval(() => {
      console.log('tick');
    }, 1000);
  };

  const stopTimer = () => {
    console.log('stopping timer: ', timer);  // shows null, instead of giving the timerId to stop properly
    clearInterval(timer);
  };

每次重新渲染组件时,
定时器
变量将“重置”。即使它保存了计时器,重新渲染也会再次将其值设置为
null

您可以移出组件范围,或者使用
useRef
通过重新呈现来保留变量:

const SomeComponent = ({ isPlaying }) => {
  const timer = React.useRef(null);

  React.useEffect(() => {
    if (isPlaying) {
      startTimer();
    }

    return () => clearInterval(timer.current);
  }, [isPlaying]);

  const startTimer = () => {
    timer.current = setInterval(() => {
      console.log('tick');
    }, 1000);
  };

  const stopTimer = () => {
    clearInterval(timer.current);
  };

请注意,我还通过在useEffect中使用返回来强制执行
clearInterval
。这样,组件将在卸载时自动“清理”。我还将计时器更改为常量。

ahhh useRef!!非常感谢。我现在就去试试。这个问题已经讨论了好几个小时了。“return()=>clearInterval(timer.current);”应该像卸载组件一样吗?目前正在试验功能组件,这是我下一个研究主题。谢谢你是的,有点。请参阅:。它将在组件卸载时运行,也会在效果再次运行时运行,即
isPlaying
更改时运行。如果只想在卸载时使用它,可以在返回函数中添加一些逻辑。