【问题标题】:React Native cancel animation delay when component will unmountReact Native 在组件卸载时取消动画延迟
【发布时间】:2016-07-07 19:47:29
【问题描述】:

我的动画有点问题。我尝试在我的应用程序上针对错误执行 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
});

如果我在动画延迟期间保持在我的视图上,那效果很好,但是如果我在消息设置为可见时转到我以前的视图,则在我的组件未安装时调用函数 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.

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

在我的研究过程中,当组件将卸载时,我找到了一种临时方法,即使用 setTimeout() 函数和 clearTimeout,但我找不到如何在 Animated.sequence 中使用 Animated.delay 函数,是吗可能吗?

提前感谢您的回答!

TLDR;

组件卸载时可以取消动画延迟吗?

【问题讨论】:

  • 文档提到了stopAnimation 方法。你试过调查吗?这是here
  • 感谢 Hamaide,但是,是的,我也尝试过,但是找不到 Animated.sequence 的函数 stopAnimation

标签: animation react-native settimeout delay


【解决方案1】:

你给Animated.start()的函数是用一个声明动画是否成功运行到最后的对象来调用的。如果组件被卸载,React-Native 也会隐式取消你的动画。所以检查你的回调中的finished-property,如果动画运行到最后,只检查setState

所以这应该有效:

...

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

(请注意,如果您手动停止动画,例如使用Animated.stop() 或使用相同的Animated.Value 启动另一个动画,则finished 属性也将是false。)

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

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多