【问题标题】:Can I call setState() from a setTimeout()?我可以从 setTimeout() 调用 setState() 吗?
【发布时间】:2019-05-15 18:39:15
【问题描述】:

我的组件中有以下代码:

  • 我通过使用setPosition(-0.08) 调用 setState 来开始反弹效果
  • 然后我使用 ref 存储 setTimeout 并在 350 毫秒后调用 setPosition(0)
function changeImage(dir) {

  const isBouncing = useRef(false);
  const bounceTimeout = useRef(null);
  // ... some other code

  if (dir === 'LEFT' && selected === 0) {
      isBouncing.current = true;
      setPosition(-0.08);
      bounceTimeout.current = setTimeout(()=> { 
        isBouncing.current = false;
        setPosition(0);
      }, 350);
      return;
    }
}

它按预期工作!

问题

我有什么理由不应该这样做(从 setTimeout)?

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    您可以通过setTimeout 拨打setState。例如,这是实现动画的方法之一。

    但在你的情况下,你应该将你的代码移动到useEffect钩子,否则可能会导致副作用。

    你还需要清除卸载超时

    useEffect(() => {
      return () => {
        if (bounceTimeout.current !== null) {
          clearTimeout(bounceTimeout.current)
        }
      }
    }, [])
    

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 2012-01-15
      • 2020-11-17
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2023-01-12
      • 2012-09-03
      • 2020-04-11
      相关资源
      最近更新 更多