Answer the question
In order to leave comments, you need to log in
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
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));
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question