Skip to content
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

列表组件中为什么要用key #16

Open
zonglang opened this issue Jul 10, 2019 · 1 comment
Open

列表组件中为什么要用key #16

zonglang opened this issue Jul 10, 2019 · 1 comment

Comments

@zonglang
Copy link
Owner

zonglang commented Jul 10, 2019

手动更新dom才是最优的,你来你来

diff原理

在交叉对比中,当新节点跟旧节点头尾交叉对比没有结果时,

  • 若存在key

根据新节点的key去对比旧节点数组中的key,从而找到相应旧节点(这里对应的是一个key => index 的map映射)。如果没找到就认为是一个新增节点。

  • 若不存在key

新节点直接复用第一个老节点(同一个组件的情况下)

key能提高效率?

不对,diff算法本身,为了提高效率,默认就是采用就地复用的模式。
但是就地复用会带来一个弊端:组件内部如果有状态,也会保留下来。

对于有内部状态的组件,

就地复用会保留内部状态,这个副作用有两种解决办法

  1. props传入 + componentWillReceiveProps更改状态
  2. 使用不同的key,强制重新装载组件(性能差一点)

对于列表渲染,

性能:key相同的patchVnode > 不使用key的patchVnode > key不同的销毁/创建

这个关系也不太准确,移动dom比修改dom性能更高的时候,使用key是高效的

其实不使用key,即默认key全部为undefined

没有key会怎样?

没有key,就无法优化一部分场景:移动组件位置,但是想要保留该组件状态。

框架强制使用key

key用index赋值,和不使用key是等价的。
所以具体怎么用不用key,操作权还是在开发者手中。

一场关于key的讨论
vue2.0的diff算法
vue patch源码

@zonglang
Copy link
Owner Author

字符串的最短编辑算法,利用动态规划,时间复杂度是O(m*n)
一棵树,转换成另一颗树的的时间复杂度是O(n^3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant