Before upgrading react to version 16.3
, I'd call a method based on changes in props like this :
componentWillReceiveProps(nextProps){
if(this.props.country.length !== nextProps.country){
doSomething(); //example calling redux action
}
}
componentWillReceiveProps
is unsafe on Version 16.3
and we must use getDerivedStateFromProps
. However, this method returns an object and I don't know how I can call a method from inside it the same way I do with componentWillReceiveProps
Yes, you need to return an object, which is the new state that that is derived from nextProp
. According to docs:
getDerivedStateFromProps
should return an object to update state, or null to indicate that the new props do not require any state updates.
But since you are not updating your state in any way inside your componentWillReceiveProps
, you should use componentDidUpdate
instead of getDerivedStateFromProps
:
componentDidUpdate(prevProps){
if ( prevProps.country !== this.props.country.length ) {
doSomething(); //example calling redux action
}
}
For this situation, it was good for the OP to use componentDidUpdate
but I found myself needing getDerivedStateFromProps
so I had to make my custom function static as well and call it using the class' name inside getDerivedStateFromProps
. Something like this:
componentDidMount() {
const something = ClassComponentName.runThisFunction();
this.setState({ updatedSomething: something });
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.key !== prevState.key) {
return {
updatedSomething: ClassComponentName.runThisFunction()
};
}
return null;
}
static runThisFunction() {
//do stuff and return value
}
To clarify, this is updating the component's state on load as well as when new props arrive. This definitely took me back to my typed-language days. Hope it helps!
if you need to call a function in "getDerivedStateFromProps", you can put this function in state in constructor , then get this function in "getDerivedStateFromProps" from state.
put function in state in constructor:
constructor(props){
super(props);
this.state = {
func1:this.func1.bind(this)
}
}
get function from state in getDerivedStateFromProps:
getDerivedStateFromProps(props,state){
return {
model:state.func1(props.model)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With