Reactjs - Setting State from props using setState in child component

javascript, reactjs

Solution

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 });


}

Problem

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?

Original source