Calling a method inside getDerivedStateFromProps in React
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)
}
}