ReactJS: Why shouldn't I mutate nested state?

前端 未结 3 1401
北海茫月
北海茫月 2021-01-19 13:28

I\'ve read the ReactJS documentation about setState. Specifically, this line:

NEVER mutate this.state directly, as calling setState() afterwa

3条回答
  •  暖寄归人
    2021-01-19 14:16

    The reason is that you miss out on the callbacks associated with this.setState and they claim that you may overwrite data by just assigning straight to the object.

    Also, often in OOP (I don't know how many stars JS gets...) you'll use getter and setter methods instead of directly manipulating the object. In this example via this.state.prop1 = "xyz";

    I've never had react overwrite my directly set state properties. The temptation to code it this way may be write to state without re-rendering. But if you're doing that you may think about not putting those in state anyways.

    If re-rendering performance is an issues checkout https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate

提交回复
热议问题