【问题标题】:How to stop function execution if the same function is already executing?如果相同的函数已经在执行,如何停止函数执行?
【发布时间】:2021-06-27 07:46:24
【问题描述】:

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

我从 onclick 和 touchend 事件中调用此函数。

如果动画仍在进行中,我想阻止此函数运行/调用。

奇怪的是,在下面的代码中,即使来自 console.log(isLoading) 的 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
    }
  };

我尝试过 Julien Ripet 的回答,但遇到了同样的问题。 现在使用该代码:

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 函数。我无法解释这种行为。

【问题讨论】:

  • 我需要知道动画是否正在播放。如果我只允许函数在动画结束时运行,我最初将无法运行它。并且 onStart 几乎在单击按钮的同时发生,因此也没有用。我也不知道如何使用动画迭代事件,因为如果我只是检查它是否存在,我可能不会进入交互实际触发的那一刻。感谢您的尝试!
  • 我认为你的组件在应用动画后会重新渲染。
  • 动画结束后会重新渲染。但这有什么帮助呢?

标签: javascript reactjs


【解决方案1】:

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

你也许可以将你的逻辑转移到一个 useEffect 钩子上,观察 isLoading 状态?

更多信息请见this question

【讨论】:

  • 我很乐意这样做,但要调用函数 changeItem 我需要参数“mod”和“index”,例如 onClick={() => changeItemHandler(0, i) } 发生。由于我不能将这些参数传递给 useEffect(因为我实际上不能调用 useEffect),所以这是不可能的。可能我可以创建一个包含所有属性的对象:“isLoading”、“mod”和“index”属性,但由于它是异步的,我会遇到同样的问题。
  • @dac0n 我认为您制作包含所有 3 个对象的想法可行。当您的用户单击/触摸您想要的任何内容时,您将使用所有需要的值更新一个状态,并且当useEffect 被调用时,您应该拥有所有 3 个状态。我无法测试以保证它会起作用,但也许。另一种解决方案可能是使用 lodash 的 Throttle 函数 lodash.com/docs/4.17.15#throttle
猜你喜欢
  • 2016-07-21
  • 2018-07-19
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
相关资源
最近更新 更多