React - Changing the state without using setState: Must avoid it?

后端 未结 4 2004
轮回少年
轮回少年 2020-12-19 02:55

My code works, but I have a best practice question: I have an array of objects in the state, and a user interaction will change a value of one object at a time. As far a

4条回答
  •  清歌不尽
    2020-12-19 03:26

    If you want follow react best practices, you should do shallow copy of all your array, when you change any property. Please look into "immutable" library implementation.

    But, from my experience, and from my opinion, setState method should be called if you have "shouldCompomenentUpdate" implementations. If you think, that your shallow copy will be consume much more resources, then react virtual dom checks, you can do this:

    this.state.data[0].property = !this.state.data[0].property;
    this.forceUpdate();
    

提交回复
热议问题