如何在包含APi调用的组件上停止setInterval ??
案例
.....
useEffect(() => {
getDataFromApi()
})
let count = 0;
let interval = setInterval(function(){
// increasing the count by 1
count += 1;
// when count equals to 5, stop the function
if(count === 5){
clearInterval(interval);
}
// display count
console.log(count);
}, 2000);
但如果五次后程序仍未停止
答案 0 :(得分:0)
如果您尝试仅在安装时运行一次效果,则需要向useEffect
函数中添加第二个参数。
// by putting this logic in the useEffect, you are creating a clousure that will prevent interval from being mutated on every render.
useEffect(() => {
getDataFromApi()
let count = 0;
let interval = setInterval(function(){
// increasing the count by 1
count += 1;
// when count equals to 5, stop the function
if(count === 5){
clearInterval(interval);
}
// display count
console.log(count);
}, 2000);
}, [])
代码没有停止的原因是因为每次组件重新发布时,该组件都会使对原始interval
的引用发生变异。因此,您实际上不应该在组件渲染方法中使用setInterval。
答案 1 :(得分:0)
您可以通过先创建一个间隔变量并像这样清除clearActiveInterval函数来实现此目的
let count = 0;
let interval = null;
function clearActiveInterval() {
clearInterval(interval);
}
其余的代码实现将是这样
interval = setInterval(function () {
// increasing the count by 1
count += 1;
// when count equals to 5, stop the function
if (count === 5) {
clearActiveInterval();
}
// display count
console.log(count);
}, 2000);