shoutingwei / react-learning

take notes for redux learning
0 stars 0 forks source link

reconciliation 和解,diff 算法 #6

Open shoutingwei opened 5 years ago

shoutingwei commented 5 years ago

Motivation When you use React, at a single point in time you can think of the render() function as creating a tree of React elements. On the next state or props update, that render() function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.

There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the state of the art algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree.

If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:

Two elements of different types will produce different trees.

The developer can hint at which child elements may be stable across different renders with a key prop.

In practice, these assumptions are valid for almost all practical use cases.

动机 在你使用react时,你可以认为render创建了一棵React元素树。在下一次state和props更新时,render方法会返回一个不同的React元素树。React就需要搞清楚如何能高效地更新UI来匹配最近的树。 关于用最少的步骤将一棵树转换成另一棵树会有一些普遍的方法。然而,算法复杂度达到O(n3)。 如果我们使用React,展示了1000个元素,就需要十亿次的比较。这样的消耗太昂贵。React使用了一种启发式的算法。这个算法建立在两个假设之上: 首先,两个元素如果是不同类型的,就会产生不同的树。 其次,开发者可以从唯一的key属性上推测出子元素是否相同。

这两个假设在实践中基本都能适用。

The Diffing Algorithm When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.

Diffing算法

Elements Of Different Types Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from to , or from

to , or from
shoutingwei commented 5 years ago

所以如果用index作为key 到底是会出错还是会慢?

https://www.cnblogs.com/wonyun/p/6743988.html 会出错