My question is: What is the purpose of line 29?
If I delete this line, I can also achieve the result, but when I log state value before I setState, even before add value, state’s value alreay became 5(That is the value after I click incre button).
This really confusing me.
line 27: the need to make a copy of the this.state.counters array is because it is in the components local state & you shouldn’t be modifying the state directly
line 28: you need to increment only the badge/span for the particular counter obj that was passed as argument to the handleIncrement method, but where is it positioned in the newly clone counters array? So you do a search by indexOf
line 29: at that position you ‘add’ the counter by using destructuring
One thing I was wondering is why we can’t set the state directly? … ok, answer probably in the docs … but … yeap … reading the docs now and the reason why not to update the state directly is because there many others things to be updated and setState takes care of them all … kinda of an answer to myself …
You probably know that updating the browser DOM is quite expensive (slow). Assuming that the state is never changed directly React can perform several very clever optimizations to minimize actual DOM updates. In short: The magic and performance of React relies on that you never change the state directly.
A small app may function fine when accidentially changing the state directly but as it grows you will encounter weird often not reproducible bugs that are very hard to find.