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

前端 未结 7 827
感动是毒
感动是毒 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:30

    The React docs for setState have this to say:

    NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

    There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

    setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

    Basically, if you modify this.state directly, you create a situation where those modifications might get overwritten.

    Related to your extended questions 1) and 2), setState() is not immediate. It queues a state transition based on what it thinks is going on which may not include the direct changes to this.state. Since it's queued rather than applied immediately, it's entirely possible that something is modified in between such that your direct changes get overwritten.

    If nothing else, you might be better off just considering that not directly modifying this.state can be seen as good practice. You may know personally that your code interacts with React in such a way that these over-writes or other issues can't happen but you're creating a situation where other developers or future updates can suddenly find themselves with weird or subtle issues.

    0 讨论(0)
提交回复
热议问题