我遇到了这个问题,我的间隔没有被删除。当其父级的 IntervalActive 属性更改为 false 时,它应该运行函数 stopPagination,但事实并非如此。间隔持续进行,不会停止。有人知道这是怎么回事吗?
const startPagination = () => {
if (!intervalId && intervalActive) {
const id = setInterval(() => {
paginate(1);
}, interval[1] * 1000);
setIntervalId(id);
}
};
const stopPagination = () => {
clearInterval(intervalId);
setIntervalId(null);
};
useEffect(() => {
console.log(intervalActive)
if (intervalActive) {
startPagination();
return () => {
clearInterval(intervalId);
setIntervalId(null);
};
} else {
stopPagination();
}
}, [intervalActive]);
我尝试清除所有间隔,但这不起作用,删除 useEffect 内的清理功能会创建 2 个间隔,一个可以删除和添加,另一个我不知道。
也许不是你问题的直接答案,但我通过使用
setTimeout
解决了这种令人困惑的间隔混乱
const nextPage = () => {
// your paging code here
// check if we should call the next page again
if (intervalActive) {
setTimeout(() => {
nextPage();
}, 1000);
}
};