M
M
Maksipes2019-07-19 18:05:26
React
Maksipes, 2019-07-19 18:05:26

Arrays of objects in state - how to update?

Given:
In the state array, in the array of objects.
Need to:
Update one of the objects, one of the properties.
Smart people taught me not to mutate state and do something like this:

onItemHintClick = (index, e) => {
    const newItems = this.state.items.map((item, i) => {
      if (i === index) {
        return { ...item, htogle: !item.htogle };
      } else {
        return {...item};
      }
    });
    this.setState({ items: newItems });
  };

Those. in the loop, an array clone is collected from the array in state, where one property changes, one element.
I'm just starting to learn React and JS and it seems strange to me - for the sake of a simple operation, arrange such a fuss.
And if there are many elements in the array and they are large in themselves?
After all, there is a direct and elegant way to change the desired value, to do, for example, like this:
this.state.items[index].htogle = !this.state.items[index].htogle
this.forceUpdate();

And now I ask for attention - I know that official documentation opposes this method, where it says - do not mutate state and avoid forceUpdate (), this can lead to unpredictable bugs.
So I want to ask - WHY this can not be done and WHAT negative consequences can this have?
It is in this case where it is not planned to use houldComponentUpdate() and other advanced application state management techniques.
It seems to me that in simple situations, mutating state and immediately calling forceUpdate() will work just as well as setState, while the code will be clearer and more efficient.
PS. please don't send me to read the documentation, those phrases about setState and forceUpdate() - I want to understand, not just blindly follow.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lnked, 2019-07-19
@maksipes

onItemHintClick = (index, e) =>
  this.setState(({ items }) => ({
    items: [
      ...items,
      [index]: {
        ...items[index],
        htogle: !items[index].htogle,
      },
    ],
  }));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question