forked from Matt-Esch/virtual-dom
-
Notifications
You must be signed in to change notification settings - Fork 7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
前沿技术解密——Virtual DOM #1
Comments
一目鸟然,甚好!可惜github不能点赞 |
@litten 谢腾爷点赞 |
👍 |
Closed
只是讲了整个大致过程,还是没有讲清楚Diff算法的具体做法 |
@freestyle21 |
你好,请问React中的component 里的key具体起到什么作用呢?如果没有的话好像也不会让程序产生异常,只会有个警告,那代表key是不是可有可无呢? |
@luokuning 以key来辨认data是否是同一个,避免深遍历 |
@miniflycn 那么作用就是能提高性能吗?没有的话也没影响? |
@luokuning 没有 |
@miniflycn 明白了,谢谢 :-) |
open for meeting |
非常赞 |
我QQ289880020 到时候请教下你 |
react diff 完了 后要更新视图上改变部分,怎么样找到要更新的节点 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
VTree
VTree模型非常简单,基本结构如下:
所以我们很容易写一个方法来创建这种树状结构,例如React是这么创建的:
VTree -> DOM
这方法也不太难,我们实现一个简单的:
diff(VTree, VTree) -> PatchObject
差异算法是Virtual DOM的核心,实际上该差异算法是个取巧算法(当然你不能指望用O(n^3)的复杂度来解决两个树的差异问题吧),不过能解决Web的大部分问题。
那么React是如何取巧的呢?
如图,React仅仅对同一层的节点尝试匹配,因为实际上,Web中不太可能把一个Component在不同层中移动。
还记得之前在VTree中的属性有一个叫key的东东么?这个是一个VNode的唯一识别,用于对两个不同的VTree中的VNode做匹配的。
这也很好理解,因为我们经常会在Web遇到拥有唯一识别的Component(例如课程卡片、用户卡片等等)的不同排列问题。
React提供自定义元素,所以匹配更加简单。
patch(DOMNode, PatchObject) -> DOMNode
由于diff操作已经找出两个VTree不同的地方,只要根据计算出来的结果,我们就可以对DOM的进行差异渲染。
扩展阅读
具体可参考下面两份代码实现:
The text was updated successfully, but these errors were encountered: