what is the preferred way to mutate a React state?

前端 未结 4 1144

Let\'s say I have a list of plain objects in my this.state.list that I can then use to render a list of children. What then is the right way to insert object in

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 10:11

    concat returns a new array, so you can do

    this.setState({list: this.state.list.concat([newObject])});
    

    another alternative is React's immutability helper

      var newState = React.addons.update(this.state, {
          list : {
            $push : [newObject]
          }
      });
    
      this.setState(newState);
    

提交回复
热议问题