当组件将卸载时,React Native取消动画延迟

Jér*_*rin 1 animation delay settimeout react-native

我对动画有点问题。我尝试在我的应用程序上执行Flash Bar Info以获取错误。为此,我创建了一个新组件,可以将该组件放置在一个特定的视图中,也可以不放置在一个特定的视图中,并且当我的商店触发错误时,componentWillReceiveProps如果有错误消息,则该组件的状态将被更改并设置为可见。

因此,如果没有错误消息,我的渲染函数返回false值,但是如果有错误消息,我使用以下动画代码运行渲染函数:

// Ease in ease out anitmation
Animated.sequence([
  Animated.timing(this.state.translateY, {
    toValue: 40,
    easing: Easing.bounce, // Like a ball
    duration: 450,
  }),
  Animated.delay(3000),
  Animated.timing(this.state.translateY, {
    toValue: 0,
    duration: 300,
  }),
]).start(() => {
  this.props.clearMessage();
  this.setState({ visible: false }); // <-- Problem is here
});
Run Code Online (Sandbox Code Playgroud)

如果在动画延迟期间停留在视图上,则效果很好,但是如果在将消息设置为可见时转到上一个视图,setState则在未安装组件时调用该函数。所以我得到了警告:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
Run Code Online (Sandbox Code Playgroud)

这是正常现象,因为此时尚未安装组件。因此,我尝试找到一种方法来在卸载组件时取消动画序列。

在研究过程中,我找到了一种在组件将要卸载时使用setTimeout()function 的临时方法clearTimeout,但是我找不到如何Animated.delay在an 中使用function进行操作Animated.sequence,这可能吗?

预先感谢您的回答!

TLDR;

当组件将要卸载时,可以取消动画延迟吗?

mtk*_*one 5

赋予您的函数Animated.start()带有一个对象,该对象声明动画是否成功结束。如果组件已卸载,React-Native也会隐式取消动画。因此finished,只有setState在动画播放到最后时,才在回调中检查-property 。

所以这应该工作:

...

]).start((done) => {
  if (done.finished) {
    this.props.clearMessage();
    this.setState({ visible: false });
  }
});
Run Code Online (Sandbox Code Playgroud)

(请注意,如果您使用例如Animated.stop()或通过启动另一个动画来手动停止动画Animated.Value,则finished-property也将是false。)

参见:https : //facebook.github.io/react-native/docs/animated.html#working-with-animations