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

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

    the simplest answer to "

    Why can't I directly modify a component's state:

    is all about Updating phase.

    when we update the state of a component all it's children are going to be rendered as well. or our entire component tree rendered.

    but when i say our entire component tree is rendered that doesn’t mean that the entire DOM is updated. when a component is rendered we basically get a react element, so that is updating our virtual dom.

    React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn’t update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.

    then react will figure out what is changed and based on that it will update the real DOM accordingly .

    hope it helps.

提交回复
热议问题