这不是一个愚蠢的问题,这是我见过许多人努力解决的问题.让我澄清这一点:
- 为什么点击处理程序上的
SetInterval
没有停止,而我已经在函数中清除了它?
发生这种情况是因为您的组件呈现了不止一次(因此您创建了多个间隔,而只清除了最后一个间隔).
- 为什么def的值在
setInterval
中没有更新.
这里有两件事需要考虑,首先,setInterval
回调不包括在Reaction生命周期中,因此值不会更新.最后,由于您只更改了变量的值(而不是组件状态),因此不会重新呈现组件,并且代码将保持不变.
您可以在Reaction Here->;https://overreacted.io/making-setinterval-declarative-with-react-hooks/中找到一篇处理间歇的非常好的文章
我还给您留下了这里的代码以及代码片段链接:
import "./styles.css";
import { useEffect, useRef, useState } from "react";
export default function App() {
const [runInterval, setRunInterval] = useState(true);
const [counter, setCounter] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
if (runInterval) {
intervalRef.current = setInterval(() => {
setCounter((c) => c + 1);
}, 1000);
}
return () => {
clearInterval(intervalRef.current);
}; // clear interval when unmounting the component
}, [runInterval]);
const clear = () => {
setRunInterval(false);
};
return (
<div className="App">
<h1 onClick={() => clear()}>Click me to Stop Interval</h1>
<h2>{counter}</h2>
</div>
);
}
https://codesandbox.io/s/stoic-elbakyan-u5ezc3?file=/src/App.js:0-734个