Amanda-Zhang
追梦女一枚

虚拟DOM和Diff算法

2021-06-17 React
Word count: 289 | Reading time: 1min

当我们更新了state中的值的时候,React会去调用render()方法来重新渲染整个组件的UI,但是如果我们真的去操作这么大量的DOM,显然性能是堪忧的。所以React实现了一个Virtual DOM,组件的真实DOM结构和Virtual DOM之间有一个映射的关系,React在虚拟DOM上实现了一个diff算法,当render()去重新渲染组件的时候,diff会找到需要变更的DOM,然后再把修改更新到浏览器上面的真实DOM上,所以,React并不是渲染了整个DOM树,Virtual DOM就是JS数据结构,所以比原生的DOM快得多。

用算法实现虚拟DOM:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function VDOM(tagName, props, children) {
this.tagName = tagName;
this.props = props;
this.children = children;
}
VDOM.prototype.render = function() {
// 建立一个真实元素
var el = document.createElement(this.tagName);

// 往该元素上添加属性
for (var name in this.props) {
el.setAttribute(name, this.props[name]);
}

// children是一个数组
var children = this.children || [];
for (var child of children) {
var childEl = (child instanceof VDOM) ? child.render() : document.createTextNode(child);
// 无论childEl是元素还是文字节点,都需要添加到这个元素中。
el.appendChild(childEl);
}
return el;
}

Author: Amanda-Zhang

Link: http://chunchunya.github.io/2021/06/17/%E8%99%9A%E6%8B%9FDOM%E5%92%8CDiff%E7%AE%97%E6%B3%95/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
浏览器渲染
NextPost >
react相关
CATALOG