【问题标题】:React Interval not stopping after Leaving离开后反应间隔不停止
【发布时间】:2020-11-23 08:58:25
【问题描述】:

我的问题是我在useEffect 中使用的间隔在离开组件时没有停止。

代码是:

useEffect(() => {
    const timer = window.setInterval(() => {
      refreshSave();
    }, 3000);
    return () => {
      window.clearInterval(timer);
    };
  }, []);

我正在考虑为空的span 设置动画,然后使用onAnimationIteration 触发保存。

【问题讨论】:

标签: javascript reactjs react-hooks setinterval


【解决方案1】:

我之前遇到过类似的问题,通过使用 useRef 钩子解决了。


const funRef = useRef(null);

//...

useEffect(() => {
    funRef.current = setInterval(() => {
      refreshSave();
    }, 3000);
    return () => {
     clearInterval(funRef.current);
    };
  }, []);

了解更多:timer app

【讨论】:

    【解决方案2】:

    您并没有真正给我们提供太多的工作背景(例如,“离开组件”是什么意思?),所以我们有点在黑暗中拍摄。

    不过,作为第一步,您可以尝试全局地声明timer变量:

    let timer;     // <- put here
    useEffect(() => {
        timer = window.setInterval(() => {
          refreshSave();
        }, 3000);
        return () => {
          window.clearInterval(timer);
        };
      }, []);
    

    【讨论】:

      猜你喜欢
      • 2015-05-16
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 2018-03-15
      相关资源
      最近更新 更多