1. 程式人生 > >深入理解React 之 Virtual DOM & Diff Algorithm

深入理解React 之 Virtual DOM & Diff Algorithm

Introduction

本學期選了“軟體體系結構”這門課,結課作業是小組恢復React的軟體體系結構。在Functional View部分,我負責瞭解React的虛擬DOM和Diff演算法,下面是我的一些理解。(根據結題報告要求,以下內容大部分用英文呈現,本人英語水平有限,希望各位看官批評指正

Virtual DOM

An Example

To begin with, let’s have a look at this code.

const title = <h1 className="title">Hello, world!</h1>;

This statement uses a new syntax name JSX

, which allows us to write HTML segments within JavaScript code. In fact, the code above will be converted into the corresponding code below.

const title = React.createElement(
    'h1',
    { className: 'title' },
    'Hello, world!'
);

Traditional workflow of browser engines

  1. HTML Parser will analyze elements in HTML files to build a DOM Tree
    .
  2. CSS Parser will analyze CSS files and inline styles defined in them and generate a Style Table of the page.
  3. Attachment will link DOM Tree and Style Table above and create a Render Tree. Actually, each DOM node in the DOM Tree has a method named “attach” which get the style information and return an object of render. These objects of render will make up a Render Tree.
  4. Given the Render Tree, the browser will start to set the layout. Every node in the Render Tree will be allocated a precise coordinate on the screen.
  5. The method named “paint” of each node will be called to show the node.

在這裡插入圖片描述 Previously, when the DOM is modified, the browser will run the workflow above through, which can cost a lot of time. When there are ten modifications on the DOM, the browser will run the procedure ten times. However, as we all know, we can run the procedure to set ten modifications only in one time, while the computer cannot do that. Virtual DOM is designed to solve this bottleneck. It can save the ten modifications in one local instance of JavaScript to avoid unnecessary cost of repeated updating of DOM Tree.

References