I often come to this sort of situation when using statefull React components.
I need to do some operation on props - either do some processing which I do now want to have in render()
or set state according the values in props.
As I want to do this when component is initially mounted as well as when the props are updated, I end up with a boilerplate code like this:
constructor(){
super(props)
const modifiedProps = doSomethingWithProps(props)
...
this.state = {initialState}
}
componentWillReceiveProps(nextProps) {
const modifiedProps = doSomethingWithProps(nextProps)
...
this.setState({newState})
}
doSomethingWithProps(props){
...
}
Is there a better way how to do this ?
Answering based on the question's comments, which I found quite helpful --
If there's a bunch of work that needs to be done based on props
, componentWillMount
allows you to use this.setState()
in your helper functions and minimize the work that's done in the constructor
. This can clean up a bunch of otherwise duplicated code.
constructor(){
super(props)
this.state = {initialState}
}
componentWillMount() {
this.doSomethingWithProps(this.props);
}
componentWillReceiveProps(nextProps) {
this.doSomethingWithProps(nextProps)
}
doSomethingWithProps(props){
...
this.setState({newState})
}
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