I'm having the following class that renders users based on a sort dropdown. Users will be listed in alphabetical order if i choose "alphabetical" and in group order when i choose "group".
render(){
return(
const {members, sort} = this.state
{ sort === "alphabetical" && <SortByAlphabet members={members} /> }
{ sort === "group" && <SortByGroup members={members}/> }
)
)
In <SortByAlphabet />
component I am setting a component state object from props.members in componentWillReceiveProps()
function.
componentWillReceiveProps = props => {
this.setState({ members : props.members });
}
When I choose "group" sort, <SortByAlphabet />
component is unmounting and <SortByGroup />
is mounting in the DOM. Again when i switch back to "alphabetical" sort, the state variable (members) that was set previosly in <SortByAlphabet />
component becomes NULL because the component was removed from the DOM.
componentWillReceiveProps
function is not triggering the second time when re-rendering <SortByAlphabet />
b'coz the props didn't change. But i want to update the state variable like i did it for the first time in componentWillReceiveProps
function.
How to do that?
componentWillMount is called only once in the component lifecycle, immediately before the component is rendered. It is usually used to perform any state changes needed before the initial render, because calling this.setState in this method will not trigger an additional render So you can update your staate using
componentWillMount ()
{
this.setState({ members : props.members });
}
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