简体   繁体   中英

Are there three tree's involved in the React Virtual Dom, or just two?

With the React virtual Dom, I understand the subtree part, or at least I think I do: React will only re-render from components that had their setState called, and potentially all children of these components. ie components that haven't had their setState method called, nor are children of a component that did, are safe from re-render.

The part I'm unclear of, is when React does its reconciliation process on these nodes, what exactly is it comparing? I believe at this step in time we have a newly generated virtual dom tree, but does it compare this to the old virtual DOM tree, and then apply those changes to the actual DOM, or is this reconciliation process done between the newly generated virtual DOM, and the actual DOM directly?

Depending on the answer to the above, I might have a follow up question. Thanks!

React compares next virtual dom with previous virtual DOM, and only applies updates if they are different.
React is ignorant of any direct changes to real DOM. If it is not in react's virtual DOM, then react does not know about it.

Codepen here with - sort of - proof of concept, containing buttons to change state, do direct DOM update, and re-render:

Code snippet from codepen:

illegalUpdate() {
  // Illegal direct DOM update, 
  // to check whether component is destroyed after re-render
  document.getElementById("id1").style.backgroundColor = "red";
}

render() {
  ...
  return (
    <div>
      {component1}
      {component2}
      <p><button onClick ={() => this.illegalUpdate()}>
    </div>
  );
}

Summary:

  • you can illegally change real DOM color of a component from green to red and then re-render.
  • component color stays red (even though the component's code sets color to green)
  • react is not aware of the change made in real DOM.
  • react compares new virtual DOM with old virtual DOM.
  • In both the color is green.
  • So no update: color stays red.

Further experiment: - If you legally change the type of component from p to H1 or vice versa, react will replace entire DOM element. So then component will appear green again.

For further reading, you could also check outreact page on advanced performance , with good explanation of virtual dom and rendering applied to component trees (including role of shouldComponentUpdate ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM