gpt4 book ai didi

javascript - 为什么我无法清除我的 setInterval?

转载 作者:行者123 更新时间:2023-12-04 08:04:17 32 4
gpt4 key购买 nike

我正在尝试创建一个 自动计数器当组件(例如此处的 Home)在 View 中呈现时。计数器应该从 1 开始并在 10 停止。但是我无法在 10 处清除我的 setInterval。计数器保持递增。
问题是什么?
非常感谢。

export const Home = () => {

const [counter, setCounter] = useState(1)
let timer = useRef()


const animate = () => {
if(counter === 10){
clearInterval(timer.current)
}else{
setCounter((previous) => previous + 1)
}
}


useEffect(() => {
timer.current = window.setInterval(() => {
animate()
}, 900)

}, [])



return (
<div style={{textAlign: "center"}}>
<h1>{counter}</h1>
</div>
)
}

最佳答案

问题是 animate 的关闭函数超过 counter 的初始值,即 1. 结果,条件 counter === 10从不评估为真。
这就是为什么您永远不应该对 useEffect 的依赖项撒谎的原因。钩。这样做可能会导致错误,因为关闭了组件先前渲染中的陈旧值。
解决方案
你可以摆脱animate()函数并在 useEffect 中编写逻辑钩。

function App() {
const [counter, setCounter] = React.useState(1);
const counterRef = React.useRef(counter);

React.useEffect(() => {
const id = setInterval(() => {
// if "counter" is 10, stop the interval
if (counterRef.current === 10) {
clearInterval(id);
} else {
// update the "counter" and "counterRef"
setCounter((prevCounter) => {
counterRef.current = ++prevCounter;
return prevCounter;
});
}
}, 900);

// clearn interval on unmount
return () => clearInterval(id);
}, []);

return (
<div style={{ textAlign: "center" }}>
<h1>{counter}</h1>
</div>
);
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于javascript - 为什么我无法清除我的 setInterval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66305137/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com