无法使用位于 React Hook 外部的变量清除间隔。

4

我试图在clearTimer方法中访问clearTimerInterval,但是得到了未定义的结果,得到了警告React Hook内部变量在每次渲染后都会丢失。在下面的代码中,useEffect钩子只被调用一次,那么为什么变量clearTimerInterval会变成未定义呢?

function Child(props) {
          let [timerCount, setTimer] = useState(0);
          var clearTimerInterval;
          useEffect(() => {
            clearTimerInterval = setInterval(() => {
              setTimer(timerCount => {
                return timerCount + 1;

              });
            }, 1000);
            return () => {
              clearInterval(clearTimerInterval);
            };
          }, []);

          function clearTimer() {
            clearInterval(clearTimerInterval);
          }
          return (
            <div>
              <div>Timer {timer}</div>
              <button onClick={clearTimer}>ClearTimer</button>
            </div>
          );
        }

        export default React.memo(Child);

这个回答解决了你的问题吗?为什么当我调用“StopTimer”函数时,我的变量“intervalId”没有得到更新?(https://stackoverflow.com/questions/60467384/why-my-variable-intervalid-is-not-getting-the-value-updated-when-i-call-the-fu) - Junius L
2个回答

9
如果您需要在重新渲染时保存变量,请使用useRef,在这种情况下,它就像类实例字段一样运作,同时请注意,对引用的更改不会触发重新渲染。
这将使您能够从useEffect之外清除间隔。
function Child(props) {
  let [timerCount, setTimer] = useState(0)
  const intervalRef = useRef(null)

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setTimer(prevState => prevState + 1)
    }, 1000)

    return () => clearInterval(intervalRef.current)
  }, [])

  function clearTimer() {
    clearInterval(intervalRef.current)
    intervalRef.current = null
  }

  return (
    <div>
      <div>Timer {timerCount}</div>
      <button onClick={clearTimer}>ClearTimer</button>
    </div>
  )
}

好的,我明白了。 - Abdul Basit Mangat

-1
尝试在钩子内部定义变量。

          useEffect(() => {
          var clearTimerInterval;
            clearTimerInterval = setInterval(() => {
              setTimer(timerCount => {
                return timerCount + 1;

              });
            }, 1000);
            return () => {
              clearInterval(clearTimerInterval);
            };
          }, []);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接