ReactJS - setState of Object key in Array

后端 未结 2 1452
无人共我
无人共我 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 20:49

    Get current state, modify it and setState() it:

    var stateCopy = Object.assign({}, this.state);
    stateCopy.items[key].upVotes += 1;
    this.setState(stateCopy);
    

    Note: This will mutate the state. Here's how to do it without mutation:

    var stateCopy = Object.assign({}, this.state);
    stateCopy.items = stateCopy.items.slice();
    stateCopy.items[key] = Object.assign({}, stateCopy.items[key]);
    stateCopy.items[key].upVotes += 1;
    this.setState(stateCopy);
    
    0 讨论(0)
  • 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 });
    
    0 讨论(0)
提交回复
热议问题