首页 > 解决方案 > 使用本机驱动程序停止 Animated.loop - 因此它会触发启动回调

问题描述

我正在运行这样的循环:

    const anim = new Animated.Value(0);

    const res = Animated.loop(
        Animated.timing(anim, {
            duration: 2000,
            toValue: 1,
            easing:Easing.inOut(Easing.linear),
            useNativeDriver: true,
            isInteraction: false
        })
    );
    res.start(e => console.log('anim stopped, e:'));

    setTimeout(()=>res.stop(), 5000); // does not trigger callback
    // setTimeout(()=>anim.stopAnimation(), 5000); // does not trigger callback

动画运行,并正确循环。(动画值在每个循环开始时回到 0)。

如果我这样做res.stop()或,动画就会停止anim.stopAnimation()。但是启动回调永远不会触发。我担心某些东西仍在运行,我可能有内存泄漏。您能否就如何正确停止本机驱动程序循环提出建议?

标签: react-native

解决方案


虽然我在文档中找不到它,但onComplete该类型上有一个可用的可选键(我在 repo的Animation.jsAnimationConfig顶部找到了它)。现在,通过在配置中添加回调来停止动画时,日志将出现:

const res = Animated.loop(
    Animated.timing(anim, {
        duration: 2000,
        toValue: 1,
        easing:Easing.inOut(Easing.linear),
        useNativeDriver: true,
        isInteraction: false,
        onComplete: (e) => console.log('anim stopped, e:') // New config option
    })
);

不能保证这在未来不会是一个重大变化,但它似乎是一个非常安全的键名,所以我认为他们不会很快对其进行重构。

至于您对内存泄漏的关注,Animated.loop调用stop()子动画的方法,所以您应该不用担心。


推荐阅读