Reputation: 217
So im trying to make a component that request data from a server and i want to able to change it before i submit it somewhere else previously i would have done it li
componentWillReceiveProps(nextProps) {
if (nextProps.dwelling) {
this.state.dwelling = nextProps.dwelling;
}
if (!nextProps.saving && this.props.saving) {
this.props.history.push('/users');
}
}
}
note: the second if is also very usfull to push after a successful save.
but since componentWillReceiveProps is deprecated i was trying to do the same with getDerivedStateFromProps:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.dwelling !== prevState.dwelling) {
return {dwelling: nextProps.dwelling}
}
return null
}
Problem is getDerivedStateFromProps is called after every render method and is messing with my onChange handlers, is there any replacement for componentWillReceiveProps? i saw a post about using shouldComponentUpdate but it seems that is not the intended way to use the method.
EDIT: componentDidUpadte did the job:
componentDidUpdate(prevProps) {
if (this.props.dwelling !== prevProps.dwelling){
this.setState(() => ({dwelling: this.props.dwelling}));
}
}
Upvotes: 1
Views: 597
Reputation: 6988
First, in your componentWillReceiveProps example, you shouldn't be setting state directly. Instead, you should be calling this.setState
.
However, to answer your question... are there reasons you wouldn't choose to do this in componentDidUpdate
? That might be better than using getDerivedStateFromProps
.
Upvotes: 2