ReactJS - setState of Object key in Array

后端 未结 2 1462
无人共我
无人共我 2020-12-28 20:15

So i\'ve been working on this for awhile and felt it would be best to refactor my code so that the state is set up as an array of objects. What i\'m trying to do is increme

2条回答
  •  [愿得一人]
    2020-12-28 21:06

    It's possible to directly edit the value on your array and set the state to the modified object, considering you're not using immutable.js, that is...

    this.state.array[i].prop = 'newValue';
    this.setState({ array: this.state.array });
    

    The problem with direct editing is that React doesn't know the state changed and the update lifecycle doesn't fire. But setting the state again forces an update.

    -- EDIT --

    If state is Immutable...

    const array = this.state.array.slice();
    array[i].prop = 'newValue';
    this.setState({ array });
    

    -- EDIT 2 --

    Thanks to the selected answer I realized this would still mutate the element since the array contains only references to the object in question. Here's a concise ES6-y way to do it.

    const array = [...this.state.array];
    array[i] = { ...array[i], prop: 'New Value' };
    this.setState({ array });
    

提交回复
热议问题