Quesions About Learning Mastering React Course

Hi,All:

I’m so honored to ask you a quesion:

In Section 4 composing Components, Counter App, About implementation of handleIncrement

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.

I hope somehone can help me.Thks a loooot!

Hi Jason, let me try line by line:

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

the rest is self explanatory … hope this helps …

3 Likes

I figure it.
Thanks a lot :+1:

After spreading the counter into a new object and assigning it to counters[index]. You’re no longer working with the object in the DOM(not directly)

Try debugging all the steps, it helped me a lot. Example:

handleIncrement = (c) => {
    console.log(c);
    const counters = [...this.state.counters]; //clone
    const idx = counters.indexOf(c);
    counters[idx] = { ...c };
    counters[idx].value++;
    console.log(this.state.counters);
    this.setState({ counters });
    setTimeout(() => {
      console.log(this.state.counters);
    }, 500);
  };

ps. the reason I’m using setTimeout is because it takes (on my slow computer) a bit to update the new state

It has noting to do with the speed of your computer. It’s the way setState() works. You can read more about it in the documentation.

1 Like

Thanks mate!!! … definitely go thru the docs!

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.

2 Likes