且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在React本机应用程序中清除setInterval

更新时间:2023-01-04 11:46:21

当前,您使用 useState 挂钩存储间隔参考.每次重新渲染 App 组件时,都会重置 fun 状态,但不会与间隔完全相同.

Currently you use the useState hook to store the interval reference. At every re-render of the App component the fun state is reset, but will not be the exact same reference to the interval.

代替使用 useRef 钩子.它可以创建对间隔的引用,该间隔在重新渲染期间不会改变.这意味着引用的 current 属性中的值将始终是完全相同的.

Instead use the useRef hook. It can create a reference to the interval which will not change during re-renders. This means that the value in the current property of the reference will always be the exact same one.

最重要的是,使用 useEffect 钩子来监视何时设置或取消设置运行状态,并根据该状态启动和停止计时器.

To top it off, use the useEffect hook to watch when a running state is set or unset and start and stop the timer based on that state.

import React, { useState, useRef, useEffect } from 'react'

export default function App() {
  const [isRunning, setIsRunning] = useState(false);
  const funRef = useRef(null);

  const startTimer = () => {
    if (!isRunning) {
      setIsRunning(true);
    }
  };

  const stopTimer = () {
    if (isRunning && funRef.current !== null) {
      setIsRunning(false);
    }
  };

  useEffect(() => {
    if (isRunning) {
      funRef.current = setInterval(() => { // Save reference to interval.
        // ...
      }, 1000);
    } else {
      clearInterval(funRef.current); // Stop the interval.
    }
  }, [isRunning]);

  // ...
}