M
M
mamaanarhiya2018-02-08 01:05:45
JavaScript
mamaanarhiya, 2018-02-08 01:05:45

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

How is it different from this one?
this.setState({
      some_data: {
        ...input,
      },
    });

and why do we need these dots?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-02-08
@mamaanarhiya

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

D
Dasha Tsiklauri, 2018-02-08
@dasha_programmist

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
}

you want to change the y field, for this you need to copy all the fields and reassign y another question, why copy if you can mutate (MobX), this feature is called immutability (Redux), to understand if the state has changed, it’s faster to check if the reference to the object has changed than do a full diff, in angular next such a thing in the detector is enabled via ChangeDetectionStrategy.OnPush

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question