Why can't I directly modify a component's state, really?

前端 未结 7 833
感动是毒
感动是毒 2020-11-21 22:40

I understand that React tutorials and documentation warn in no uncertain terms that state should not be directly mutated and that everything should go through setState

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 23:21

    To avoid every time to create a copy of this.state.element you can use update with $set or $push or many others from immutability-helper

    e.g.:

    import update from 'immutability-helper';
    
    const newData = update(myData, {
      x: {y: {z: {$set: 7}}},
      a: {b: {$push: [9]}}
    });
    

提交回复
热议问题