Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Harmonic algorithm Diffing algorithm Strategy in React

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you the "React harmonic algorithm Diffing algorithm strategy example analysis", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "React harmonic algorithm Diffing algorithm strategy example analysis" this article.

Algorithm strategy

The harmonic algorithm of React mainly occurs in the render phase. The harmonic algorithm is not a specific algorithm function, but refers to a strategy, also known as diffing algorithm, which is used to improve the performance of constructing workInProcess tree and updating Dom tree in the process of reconciliation. When describing the "Diffing" algorithm on React's official website, it mentions "diffing two trees", but in the source code implementation, it is not diffing these two trees from top to bottom after creating two trees. This diffing occurs when the child node is built, and it is actually the diffing of the fibe node on the newly generated ReactElement and current tree. In order to control the time complexity of the diffing algorithm to O (n) (the time complexity of the tree diff involves the editing distance of the tree, see here), the following strategy is adopted:

Only compare nodes at the same level (it seems that this point is not mentioned on the official website)

For single-node comparison, if the current node type and key are different, no longer compare its sub-nodes, delete the node and its whole sub-tree directly, and regenerate the node tree according to ReactElement. Because React believes that different types of components generate different tree structures, there is no need for reuse.

If the child node is an array, the nodes can be compared according to the unique key value, so that even if the order of the child node changes, it can be reused according to the key value.

It is worth noting that the diffing of all nodes compares key,key to null by default. If it is not set, null is always equal to null and key is considered to be the same.

Single node diffing

When a single node performs diffing, it will diffing two sets of attributes: fibe.elementType vs ReactElement.type and fibe.key vs ReactElement.key. If these two sets of attributes are equal, the physical space of the data structure will have the following reuse logic (see the source code reconcileSingleElement function for details):

If an alternate node exists in the current fibe (which means that the fibe node has previously participated in reconciliation), the physical space of the alternate node is reused; otherwise, the clone current fibe node is required, which takes up the new physical space.

The corresponding instance or Dom will be reused

The child tree under current fibe will also be mounted directly (it will be used when recurring child nodes in the next step)

If one of the two sets of properties is not equal:

Fibe is recreated according to ReactElement

The corresponding instance and Dom will also be rebuilt

All child trees are deleted.

If the generated ReactElement is single-node, but there are multiple nodes on the corresponding current tree, it will look for matches one by one, find matches, and delete all others; if not, delete them all. For example, the Couter component has the following logic: when the number of clicks is greater than 10:00, hide the click button. When the 10th time is reached, the span node is reused.

Class Counter extends React.Component {state= {count:0} addCount = () = > {const count = this.state.count+1; this.setState ({count})} componentDidUpdate () {console.log ("updated")} render () {return this.state.count

< 10 ? [ 点击 点击次数:{this.state.count} ]:点击次数:{this.state.count}; }}数组节点diffing 数组节点进行diffing时,流程比较复杂:(源码见reconcileChildrenArray函数)

There are two important traverses in the middle, the first one is traversed by index, the new and old nodes are compared in turn, and the traversal is interrupted immediately if the key value does not match. In the second traversal, a "key-node" Map table is established for the remaining old nodes, traversing the remaining new nodes, and comparing the old nodes from the table according to the key value. The following is a comparison of the matching of new and old nodes under three kinds of case.

Requirements for the use of key values

From the diffing of single node and array node, the key value is mainly to reduce the number of new ones. In order to ensure that the new nodes can match the old nodes when diffusing, the following notes should be taken when using the key value:

It has to be stable. If the key value changes every time (for example, random numbers are used), when diffing, all the new and old sections do not match, which will cause a large number of new projects.

Must be unique, if the key value is not unique, in the establishment of the "key-node" Map table, will be omitted and confused, resulting in page update errors.

For a single node, the key value will also be used when diffusing, so don't think that it is useless and set it randomly. There are also some irregular uses, using key values for a single node to destroy and rebuild components, but this usage is not in line with the design philosophy of React.

For example, there is a logging component that pulls log data internally and has no data dependency on the outside. However, when the requirements are iterated, the approval operation is added to the same page. After the approval, the backend will add a log data. At this time, you will want the front-end page to display the new log data in real time, and you will need to trigger the log component to pull the data again. If you do not solve the problem by promoting the data up, you can assign a random key to the component, and when the approval operation is complete, modify the key value, and the component will be rebuilt. However, this method is expensive, and the entire component tree will be destroyed and rebuilt. You can use other solutions instead, for example, you can assign a ref to the component, and when the approval is completed, call the refresh function of the component through ref to retrieve the data and update the component.

For array nodes, the key value mainly plays a key role when a large dislocation occurs in the position of the child node. For normal end additions and deletions, the first index traversal can be matched, and the second key map traversal will not be entered. Because the key value requires "stability" and "uniqueness", the front end generally needs the back end to provide a unique identity for the list data, and for the aggregation interface, it will add extra work to the back end. In this case, you can first understand the changing characteristics of the data, and then decide whether it is really necessary to set key.

For the log component above, the log is a list, and the new logs are inserted in the first line. If you do not set key, basically all the child nodes will be updated. If you set key, you need the back-end service to add a "forever" unique identifier, such as id, to each log. I have experienced a case in which the page is displayed incorrectly when the data is updated because of the uniqueness of the key value.

The above is all the contents of the article "example Analysis of Diffing algorithm Strategy of Harmonic algorithm in React". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report