Want to call a method inside getDerivedStateFromProps in React? 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.