【发布时间】:2021-05-27 13:47:34
【问题描述】:
我有一个类似于分页的自动化功能,当它被按下时它会不断将数据推送到数据库中,它会按照我想要的方式工作,我唯一的问题是它无法停止,我试过了将 if 语句放在任何看起来合乎逻辑的地方,但我无法停止。
我将automate 设置为timeout 推送,因为如果没有,它会执行无限循环并尝试以超快的速度推送所有项目。
function automatePush() {
if (stop === true) return console.log("stoppped");
setMutationState(true); // this is what allowes the products to be pushed
setSliceStart((prev) => prev + 5); //pagination start
setSliceEnd((prev) => prev + 5); //pagination end
if (stop === false){ // if stop is not true then keep calling the function
setTimeout(() => {
setMutationState(false); // this just refreshes the item to keep pushing the next ones
automatePush(); // this calls itself to keep looping through items.
}, 6000);
}
}
如果我在执行automate 之前手动将stop 状态更改为true,然后单击automate,它会在控制台记录'stoppped',并且自动化不会发生,因为这是我想要的
这就是我在自动化进行时试图阻止它的方式
<div>
<p>
by clicking "Automate" you can create all the products from the
database (not including the ones you just created)
</p>
<button onClick={() => automatePush()}>Automate</button> // this is the one that calls the automate
<button onClick={() => setStop(true)}>STOP</button> // this one is the one that should stop it
</div>
【问题讨论】:
-
不确定您在这里到底要做什么,但如果变量“stop”没有改变,这是预期的行为。没有什么可以阻止递归
-
也就是说,
stop可能被闭包捕获,并且它在闭包内部没有发生变异,因此它永远不会获得更新的值。您可以使用可变的 ref 而不是 state。 -
使用超时id取消。 stackoverflow.com/questions/29526739/…