M
M
miniven2018-08-13 10:09:59
React
miniven, 2018-08-13 10:09:59

How to correctly set the initial state from props in React?

There is a list in store Redux. I display this list in the component, I can change the order of the elements and, when I click "save", write the changes to the store. Accordingly, it is necessary that the intermediate state of the list (when the order is changed, but the changes have not yet been saved) is stored in the state of the component, as I understand it. But for this, I need to initially set this state in the component. Here's how to do it, because simply setting the state from props is wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-13
@miniven

Why is it wrong? The main thing is that when changing the order of elements, the state is updated immutably.
And you can set the resulting state if you use a version below 16.3 in a React project like this:

const computeDerivedState = props => ({
  someData: props.someData,
});

class Example extends Component {
  state = {
    ...computeDerivedState(this.props),
    someState,
  };
  
  componentWillReceiveProps(nextProps) {
    if (nextProps.someData !== this.props.someData) {
      this.setState(computeDerivedState(nextProps));
    }
  }
}

If you are using React ˆ16.3 in your project, then instead of componentWillReceiveProps and computeDerivedState use getDerivedStateFromProps and read this article .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question