如果同一个函数已经在执行,如何停止函数执行



我有一个函数,它使用CSS动画动态更改页面上的对象。

我从onclick和touchend事件调用这个函数。

如果动画仍在处理中,我希望阻止此函数运行/调用。

奇怪的是,在下面的代码中,即使isLoading from console.log(isLoading(等于false,也会调用函数changeItem。

const [isLoading, setIsLoading] = useState(false);
const changeItemHandler = (mod, index) => {
console.log(isLoading);
if (isLoading === true) return;
else {
setIsLoading(true);
changeItem(mod, index);     //at the end of animation setIsLoading(false) is called
}
};

我试过朱利安·里佩尔的答案,也遇到了同样的问题。现在有了这个代码:

const [animAttrs, setAnimAttrs] = useState({isLoading: false, mod: null, index: null});
const changeItemHandler = (mod, index) => {
if (animAttrs.isLoading === true) return;
else setAnimAttrs({ isLoading: true, mod: mod, index: index });
};
useEffect(() => {
if (animAttrs.mod == null) return;  
//needed to not call this function only after click or swipe
else changeItem(animAttrs.mod, animAttrs.index);  
//onanimationend i call setAnimAttrs({isLoading:false,mod:null,index:null});
}, [animAttrs]);

即使animAttrs.isLoading===true,它也会调用changeItem函数。我无法解释这种行为。

useState钩子是异步的,因此当再次调用函数时,不会更新您的状态。

您也许可以将您的逻辑移动到useEffect挂钩,以监视isLoading状态?

请参阅此问题了解更多信息

最新更新