J
J
Jun18012018-07-09 17:05:09
JavaScript
Jun1801, 2018-07-09 17:05:09

React: Why are props updating? When do I not update them?

https://codesandbox.io/s/z29w9y4omm <- LINK TO THE CODE
There is a method changeHandlerthat works when the input changes.
It logs the state of the parent 's state What happens : for unknown reasons, when we change the local form, the logs show that the state of the parent also changes. It turns out that the "Cancel" button does not work as it should, but saves the given data (or rather, the data is written immediately to changeHandler. Please explain what is happening and how to fix it * Here - if you comment out this line, then the parent state does not change console.log(this.props.data[this.state.id]);

5b436b6b8b3b0362182935.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-09
@Jun1801

You are mutating state:
Before that, assign it a props value:

this.setState({
  data: this.props.data,
  id: this.props.id
});

Naturally props changes after mutation.
Banal example:
const a = { key: 'value' };
const b = a;
b.key = 'new value';
console.log(a.key); // new value

Read more about passing by reference. Read about immutability.
And never write anything like this again:
Changing the state only through this.setState.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question