!! 建议看英文文档,一看就会,不用看其他小伙伴的总结!,官网链接在下面。一下内容是我在官网凭自己的相法写的,不建议观看!!!l
1、Element 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 a label to img label , or from Article to Comment any of those will lead to a full rebuild。
<div>
<Counter />
</div>
<span>
<Counter />
</span>
This will destroy the old Counter and remount a new one.
2、Elements Of the Same Type
2.1、DOM Elements Of the Same Type
When comparing two React DOM elements of the same type ,React looks at the attributes of both, keep the same underlying DOM node , and only updates the changed attributes , For example:
<div className="before" title="stuff" />
<div className="after" title="stuff" />
By comparing these two elements, React knows to only modify the className on the underlying DOM node.
2.2、Component Elements Of The Same Type
When the component updates , the instance stays the same , so that state is maintained across renders . React updates the props of the underlying component instance to match the new element , and calls
UNSAFE_componentWillReceiveProps(),
UNSAFE_componentWillUpdate() and componentDidUpdate() on the underlying instance.
Next, the render() method is called and the diff algorithm recurses on the previous result and the new result.
简而言之就是 通过生命周期函数,接收比较props进行递归渲染,
3、Recursing On Children
3.1、Not Keys
<ul>
<li>first</li>
<li>second</li>
</ul>
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
but what happens when we encounter intercalated elements ?
For Example,converting between these two trees works poorly:
<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>
<ul>
<li>Connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>
简而言之:从后面放,没什么问题,不会影响算法。但是从开头放,我们就会把之前的全部删掉,从头重新渲染,非常影响算法。
3.2、Keys
In order to solve this issue, React supports a key attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a key to our inefficient example above can make the tree conversion efficient:
为了解决这个问题,React支持一个key属性。 当子树具有键时,React使用该键来匹配原始树中的子树与后续树中的子树。 例如,在上面这个效率不高的例子中添加一个键可以使树转换更有效:
<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
Now React knows that the element with key ‘2014’ is the new one, and the elements with the keys ‘2015’ and ‘2016’ have just moved.
but we try not use i as the key
DataList.map((item,i)=>{
return(
<li key={i}></li> // not try to it
<li key={item.id}></li> //used it
)
})
// if you want to know why? I will tell you to https://baidu.com