Home  >  Article  >  Web Front-end  >  What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

寻∝梦
寻∝梦Original
2018-09-11 14:58:161713browse

This article mainly tells a detailed explanation of the principles of the react framework. There is also a lot of in-depth understanding of react below. Let us take a look at this article now

I have been working on React for more than 2 years. I love and hate this framework. Everyone is familiar with its advantages, but its shortcomings are gradually exposed. In a large-scale project , when combined with third-party frameworks such as Redux and ReactRouter, the amount of complex business code will become very large (the front-end code is often 1.5 times the previous size). If the underlying design is not good in the early stage, you will often face the problem of low development efficiency. The following summarizes some core concepts of the React framework, I hope it will be helpful to everyone:

React diff algorithm

React’s diff algorithm It is the biggest reliance of Virtual DOM. We all know that the performance of a page is generally determined by the rendering speed and number of renderings. How to maximize the use of the diff algorithm for development? Let's first look at how it works.

Traditional diff algorithm

Calculate the minimum operation required to convert one tree structure into another tree structure. The traditional diff algorithm compares nodes sequentially through loop recursion, which is inefficient and complex. The degree reaches O(n^3), where n is the total number of nodes in the tree. In other words, if you want to display 1,000 nodes, you will have to perform billions of comparisons in sequence. This performance consumption is unacceptable for front-end projects.

Core Algorithm

As seen above, the complexity of the traditional diff algorithm is O(n^3), which obviously cannot meet the performance requirements. And React transforms O(n^3) complexity problems into O(n) complexity problems by formulating bold strategies. How did he do that?

tree diff

There are very few cross-level movement operations of DOM nodes in Web UI and can be ignored. React has made a concise and clear optimization of the tree algorithm, that is, hierarchical comparison of trees. Two trees will only compare nodes at the same level. As shown in the figure below:

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

React uses updateDepth to control the level of the Virtual DOM tree. Only DOM nodes in the same color box will be compared, that is, the same color will be compared. All child nodes under a parent node. When it is found that a node no longer exists, the node and its sub-nodes will be completely deleted and will not be used for further comparisons. In this way, only one traversal of the tree is needed to complete the comparison of the entire DOM tree.

// tree diff算法实现updateChildren: function(nextNestedChildrenElements, transaction, context) {
  updateDepth++;  var errorThrown = true;  try {    this._updateChildren(nextNestedChildrenElements, transaction, context);
    errorThrown = false;
  } finally {
    updateDepth--;    if (!updateDepth) {      if (errorThrown) {
        clearQueue();
      } else {
        processQueue();
      }
    }
  }
}

Why should we reduce the cross-level operations of DOM nodes?

As shown below, the A node (including its sub-nodes) is moved entirely to the D node. Since React will only simply consider the position transformation of nodes at the same level, and for nodes at different levels, only creation and deletion are required. operate. When the root node finds that A has disappeared in the child node, it will destroy A directly; when D finds that there is an additional child node A, it will create a new A (including child nodes) as its child node. At this time, the execution of React diff is: create A -> create B -> create C -> delete A.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

It can be found that when a node moves across levels, the imaginary move operation will not occur, but the tree with A as the root node will be completely re- Create, which is an operation that affects React performance.

component diff

Two components with the same class will generate similar tree structures, and two components with different classes will generate different tree structures.

  • If they are components of the same type, continue to compare virtual DOM tree according to the original strategy.

  • If not, the component will be judged as dirty component, thereby replacing all child nodes under the entire component.

  • For the same type of component, there may be no change in its Virtual DOM. If you can know this for sure, you can save a lot of diff operation time, so React Allows users to determine whether the component needs to be diffed through shouldComponentUpdate().

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

As shown above, when component D changes to component G, even if the two component have similar structures, once React determines D and G is a different type of component, so the structures of the two will not be compared, but component D will be deleted directly and component G and its sub-nodes will be re-created. Although React diff will affect performance when two component are different types but have similar structures, as the React official blog says: Different types of component There are very few opportunities for similar DOM tree, so it is difficult for such extreme factors to have a significant impact on the implementation and development process.

element diff

For a group of child nodes at the same level, they can be distinguished by a unique id. React proposes an optimization strategy: developers are allowed to add unique keys to distinguish the same group of child nodes at the same level. Although it is only a small change, the performance has undergone earth-shaking changes!

The nodes contained in the new and old sets are as shown in the figure below. The new and old sets are compared by diff. Through the key, it is found that the nodes in the new and old sets are the same nodes, so there is no need to delete and create nodes. , you only need to move the positions of the nodes in the old set and update them to the positions of the nodes in the new set. At this time, the diff result given by React is: B and D do not perform any operations, and A and C perform moving operations.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

Development Suggestions

(1)[Based on tree diff] When developing components, maintaining a stable DOM structure helps maintain overall performance. In other words, do as little dynamic manipulation of the DOM structure as possible, especially movement operations. When the number of nodes is too large or the number of page updates is too large, the page freeze phenomenon is more obvious. You can hide or show nodes via CSS without actually removing or adding DOM nodes.

(2)[Based on component diff] When developing components, pay attention to using shouldComponentUpdate() to reduce unnecessary updates of components. In addition, similar structures should be encapsulated into components as much as possible, which not only reduces the amount of code, but also reduces the performance consumption of component diff.

(3)[Based on element diff] For list structures, try to reduce operations like moving the last node to the head of the list. When the number of nodes is too large or update operations are too frequent, It will affect the rendering performance of React to a certain extent.

React Lifecycle

The life cycle of React can be divided into four situations:

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

  • When it is loaded for the first time component, execute getDefaultProps, getInitialState, componentWillMount, render and componentDidMount in order;

  • When unloading a component, execute componentWillUnmount;

  • When reloading a component, execute getInitialState# in order. ##, componentWillMount, render and componentDidMount, but does not execute getDefaultProps;

  • When the component is rendered again, the component receives the updated status. At this time,

    componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, render and componentDidUpdate.

Three states of React components

State 1: MOUNTING

mountComponent Responsible for managing in the life cycle getInitialState, componentWillMount, render, and componentDidMount.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

State 2: RECEIVE_PROPS

updateComponent Responsible for managing componentWillReceiveProps, shouldComponentUpdate in the life cycle , componentWillUpdate, render and componentDidUpdate.

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

State 3: UNMOUNTING

unmountComponent is responsible for managing componentWillUnmount in the life cycle. (If you want to see more, go to the PHP Chinese website React Reference Manual column to learn)

First set the status to

UNMOUNTING, if componentWillUnmount## exists #, then execute; if setState is called in componentWillUnmount at this time, reRender will not be triggered. The update status is NULL, and the component uninstallation operation is completed. The implementation code is as follows: <pre class="prettyprint">// 卸载组件unmountComponent: function() { // 设置状态为 UNMOUNTING this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING; // 如果存在 componentWillUnmount,则触发 if (this.componentWillUnmount) { this.componentWillUnmount(); } // 更新状态为 null this._compositeLifeCycleState = null; this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); }</pre><h2>React生命周期总结</h2> <p><img src="https://img.php.cn//upload/image/939/139/606/1536648897123010.png" title="1536648897123010.png" alt="What algorithms does the React framework have? Detailed explanation of the algorithm of react framework"></p> <table> <thead><tr class="firstRow"> <th>生命周期</th> <th>调用次数</th> <th>能否使用setState()</th> </tr></thead> <tbody> <tr> <td>getDefaultProps</td> <td>1</td> <td>否</td> </tr> <tr> <td>getInitialState</td> <td>1</td> <td>否</td> </tr> <tr> <td>componentWillMount</td> <td>1</td> <td>是</td> </tr> <tr> <td>render</td> <td>>=1</td> <td>否</td> </tr> <tr> <td>componentDidMount</td> <td>1</td> <td>是</td> </tr> <tr> <td>componentWillReceiveProps</td> <td>>=0</td> <td>是</td> </tr> <tr> <td>shouldComponentUpdate</td> <td>>=0</td> <td>否</td> </tr> <tr> <td>componentWillUpdate</td> <td>>=0</td> <td>否</td> </tr> <tr> <td>componentDidUpdate</td> <td>>=0</td> <td>否</td> </tr> <tr> <td>componentWillUnmount</td> <td>1</td> <td>否</td> </tr> <tr> <td>componentDidUnmount</td> <td>1</td> <td>否</td> </tr> </tbody> </table> <h1>setState实现机制</h1> <p><code>setStateReact框架的核心方法之一,下面介绍一下它的原理:

What algorithms does the React framework have? Detailed explanation of the algorithm of react framework

// 更新 statesetState: function(partialState, callback) {
  // 合并 _pendingState
  this.replaceState(
    assign({}, this._pendingState || this.state, partialState),
    callback
  );
},

当调用 setState 时,会对 state 以及 _pendingState 更新队列进行合并操作,但其实真正更新 state 的幕后黑手是replaceState

// 更新 statereplaceState: function(completeState, callback) {
  validateLifeCycleOnReplaceState(this);  // 更新队列
  this._pendingState = completeState;  // 判断状态是否为 MOUNTING,如果不是,即可执行更新
  if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) {
    ReactUpdates.enqueueUpdate(this, callback);
  }
},

replaceState 会先判断当前状态是否为 MOUNTING,如果不是即会调用 ReactUpdates.enqueueUpdate 执行更新。

当状态不为 MOUNTINGRECEIVING_PROPS 时,performUpdateIfNecessary 会获取 _pendingElement_pendingState_pendingForceUpdate,并调用 updateComponent 进行组件更新。

// 如果存在 _pendingElement、_pendingState、_pendingForceUpdate,则更新组件performUpdateIfNecessary: function(transaction) {
  var compositeLifeCycleState = this._compositeLifeCycleState;  // 当状态为 MOUNTING 或 RECEIVING_PROPS时,则不更新
  if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
      compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {    return;
  }  var prevElement = this._currentElement;  var nextElement = prevElement;  if (this._pendingElement != null) {
    nextElement = this._pendingElement;    this._pendingElement = null;
  }  // 调用 updateComponent
  this.updateComponent(
    transaction,
    prevElement,
    nextElement
  );
}

如果在 shouldComponentUpdatecomponentWillUpdate 中调用 setState,此时的状态已经从 RECEIVING_PROPS -> NULL,则 performUpdateIfNecessary 就会调用 updateComponent 进行组件更新,但 updateComponent 又会调用 shouldComponentUpdatecomponentWillUpdate,因此造成循环调用,使得浏览器内存占满后崩溃。

开发建议

不建议在 getDefaultPropsgetInitialStateshouldComponentUpdatecomponentWillUpdaterendercomponentWillUnmount 中调用 setState,特别注意:不能在 shouldComponentUpdatecomponentWillUpdate中调用 setState,会导致循环调用。

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of What algorithms does the React framework have? Detailed explanation of the algorithm of react framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn