问题
I've a little problem with an animation. I try to do a Flash Bar Info on my app for the errors. So to do that I create a new component, this component can be place in one specific view or not, and when the error is trigger from my store the state of my component is change by componentWillReceiveProps
and set to visible if there is an error message.
So, if there isn't an error message my render function return false value but if there is an error message I run my render function with this animation code:
// 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
});
If I stay on my view during the animation delay, that's work perfectly, but if I go to my previous view when the message is set to visible, the function setState
is called when my component is not mounted.
So I got this waring:
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.
It's a normal behavior because the component is not mounted at this point. So, I try to find a way to cancel my animation sequence when the component will unmount.
During my research I find a temporary way by using setTimeout()
function with clearTimeout
when the component will unmount, but I can't find how to do that with Animated.delay
function in an Animated.sequence
, is it possible ?
In advance thank you for your answers!
TLDR;
It is possible to cancel an animation delay when component will unmount ?
回答1:
The function you give to Animated.start()
is called with an object declaring whether the animation ran to the end successfully. React-Native also implicitly cancels your animation if the component is unmounted. So check for the finished
-property in your callback, and only setState
if the animation ran to the end.
So this should work:
...
]).start((done) => {
if (done.finished) {
this.props.clearMessage();
this.setState({ visible: false });
}
});
(Note that if you manually stop the animation, using e.g. Animated.stop()
or by starting another animation with the same Animated.Value
, the finished
-property will also then be false
.)
See: https://facebook.github.io/react-native/docs/animated.html#working-with-animations
来源:https://stackoverflow.com/questions/36128714/react-native-cancel-animation-delay-when-component-will-unmount