ReactJS - setState of Object key in Array

后端 未结 2 1463
无人共我
无人共我 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);
    

提交回复
热议问题