Answer the question
In order to leave comments, you need to log in
Why is it written in state like this in React?
Why is such a record necessary?
this.setState({
...this.state,
some_data: {
...this.state.some_data,
...input,
},
});
this.setState({
some_data: {
...input,
},
});
Answer the question
In order to leave comments, you need to log in
Firstly, in setState , the previous state does not need to be transferred to the root, so under the hood the previous state will be added to it anyway, regardless of what you pass there. Something like this:
Secondly, it is not correct to pass this.state to setState , since setState is executed asynchronously and your current state may have time to change. If you need to update the state based on the previous one, it’s a good idea to pass a function to setState , to which your state will come as the first argument when called:
this.setState(prevState => ({
some_data: {
...prevState.some_data,
...input,
},
});
a shallow-copy of the object is created, that is, the "..." ( spread operator ) operator copies the properties of the object, this is done in order not to lose data when updating one property
, let's say you had a state object of such a structure
let state = {
x:1,
y:2,
z:3
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question