Reputation: 429
With componentWillReceiveProps
being deprecated and the replacement getDerivedStateFromProps
returning a final state, how would i gradually change state over time (i.e. animate something) with the new getDerivedStateFromProps
?
with componentWillReceiveProps
, the following works fine:
state = {
itemOpacity: new Animated.Value(0.25)
};
componentWillReceiveProps(nextProps) {
if (this.props.items.visible !== nextProps.items.visible) {
let value = 0;
if (nextProps.items.visible) {
value = 1;
}
Animated.timing(this.state.itemOpacity, {
toValue: value,
duration: 200,
}).start();
}
}
how would i do something like this with getDerivedStateFromProps
? or is my animation pattern stupid?
Upvotes: 2
Views: 770
Reputation: 429
The simple answer is to just not use state for animations (thanks to dentemm for helping out):
itemOpacity = new Animated.Value(0.25);
class TestScreen extends Component {
getDerivedStateFromProps(nextProps) {
let value = 0;
if (nextProps.items.visible) {
value = 1;
}
Animated.timing(itemOpacity, {
toValue: value,
duration: 200,
}).start();
return null;
}
}
Upvotes: 1
Reputation: 6379
getDerivedStateFromProps is called with a newProps and previousState argument. So you can use previousState for the animation:
static getDerivedStateFromProps(nextProps, prevState) {
let value = 0;
if (nextProps.items.visible) {
value = 1;
}
Animated.timing(prevState.itemOpacity, {
toValue: value,
duration: 200,
}).start();
return {
// update state
}
}
Upvotes: 1