【问题标题】:Cancelling react native's react spring async animation on component unmount在组件卸载时取消 react native 的 react spring 异步动画
【发布时间】:2021-01-30 16:38:10
【问题描述】:

我有一个使用 react-spring 库循环动画的组件。 当通过“isVisible”卸载组件时,react 抱怨内存泄漏:

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。

以下是导致问题的代码的 sn-p。

有没有更好的方法/正确的方法来循环 react-spring 的动画而不会出现内存泄漏问题?

import React from 'react';
import { useTransition } from 'react-spring';

export let component = (props) => {

  const { isVisible } = props;

   const transitions = useTransition(isVisible, null, {
        config: { duration: 5000 },
        from: { opacity: 1, translateX: 500 },
        enter: item => async (next, cancel) => {
            while (isVisible) {
                await next({ config: { duration: 5000 }, translateX: -1 * 500 });
                await next({ config: { duration: 50 }, opacity: 0 });
                await next({ config: { duration: 50 }, translateX: 500 });
                await next({ config: { duration: 50 }, opacity: 1 });
            };
        },
    });
    
    return transitions.map(({ item, key, props}) => (
      <AnimatedView
        key={key}
        style={[
          {
            transform: [{ translateX: props.translateX }],
            opacity: props.opacity
          }
        ]}
      >
       {/.../}
      </AnimatedView>
    ))
}

【问题讨论】:

    标签: reactjs react-native expo react-spring


    【解决方案1】:

    您是否尝试过使用 useEffect 进行清理? 当您使用 isVisible 控制转换时,我会向它添加一个名为mounted 的开关。您可以在 useEffect 清理功能中将其关闭。所以动画会停止。

    const [mounted, setMounted] = React.useState(true);
    const isVisible = props.isVisible && mounted;
    
    useEffect(() => {
      return () => {
        setMounted(false);
      };
    }, []);
    

    【讨论】:

    • 感谢您的建议。我曾尝试在 useEffect 清理中使用控制变量,但出现同样的错误。
    【解决方案2】:

    通过直接从父组件卸载组件找到了解决此问题的方法。

    let component = () => { ... };
    
    let parent = () => {
        
        const [isVisible, setIsVisible] = useState(true);
    
        return isVisible && <Component />;
    }
    

    当组件通过 isVisible 卸载时,while 动画循环不再抛出错误

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2017-10-12
      • 2019-03-19
      相关资源
      最近更新 更多