深入理解react(源码分析)

开发 前端
首先理解ReactElement和ReactClass的概念。想要更好的利用react的虚拟DOM,diff算法的优势,我们需要正确的优化、组织react页面。

理解ReactElement和ReactClass的概念

首先让我们理解两个概念:

ReactElement

一个描述DOM节点或component实例的字面级对象。它包含一些信息,包括组件类型type和属性props。就像一个描述DOM节点的元素(虚拟节点)。它们可以被创建通过React.createElement方法或jsx写法

分为DOM Element和Component Elements两类:

  • DOM Elements

当节点的type属性为字符串时,它代表是普通的节点,如div,span

  1.   type: 'button'
  2.   props: { 
  3.     className: 'button button-blue'
  4.     children: { 
  5.       type: 'b'
  6.       props: { 
  7.         children: 'OK!' 
  8.       } 
  9.     } 
  10.   } 
  11.  
  • Component Elements

当节点的type属性为一个函数或一个类时,它代表自定义的节点

  1. class Button extends React.Component { 
  2.   render() { 
  3.     const { children, color } = this.props; 
  4.     return { 
  5.       type: 'button'
  6.       props: { 
  7.         className: 'button button-' + color, 
  8.         children: { 
  9.           type: 'b'
  10.           props: { 
  11.             children: children 
  12.           } 
  13.         } 
  14.       } 
  15.     }; 
  16.   } 
  17.  
  18. // Component Elements 
  19.   type: Button, 
  20.   props: { 
  21.     color: 'blue'
  22.     children: 'OK!' 
  23.   } 
  24.  

ReactClass

ReactClass是平时我们写的Component组件(类或函数),例如上面的Button类。ReactClass实例化后调用render方法可返回DOM Element。

react渲染过程[[174578]] 

过程理解:

  1. // element是 Component Elements 
  2. ReactDOM.render({ 
  3.   type: Form, 
  4.   props: { 
  5.     isSubmitted: false
  6.     buttonText: 'OK!' 
  7.   } 
  8. }, document.getElementById('root')); 
  1. 调用React.render方法,将我们的element根虚拟节点渲染到container元素中。element可以是一个字符串文本元素,也可以是如上介绍的ReactElement(分为DOM Elements, Component Elements)。
  2. 根据element的类型不同,分别实例化ReactDOMTextComponent, ReactDOMComponent, ReactCompositeComponent类。这些类用来管理ReactElement,负责将不同的ReactElement转化成DOM(mountComponent方法),负责更新DOM(receiveComponent方法,updateComponent方法, 如下会介绍)等。
  3. ReactCompositeComponent实例调用mountComponent方法后内部调用render方法,返回了DOM Elements。再对如图的步骤2⃣递归。

react更新机制

每个类型的元素都要处理好自己的更新:

  1. 自定义元素的更新,主要是更新render出的节点,做甩手掌柜交给render出的节点的对应component去管理更新。
  2. text节点的更新很简单,直接更新文案。
  3. 浏览器基本元素的更新,分为两块:
  • 先是更新属性,对比出前后属性的不同,局部更新。并且处理特殊属性,比如事件绑定。
  • 然后是子节点的更新,子节点更新主要是找出差异对象,找差异对象的时候也会使用上面的shouldUpdateReactComponent来判断,如果是可以直接更新的就会递归调用子节点的更新,这样也会递归查找差异对象。不可直接更新的删除之前的对象或添加新的对象。之后根据差异对象操作dom元素(位置变动,删除,添加等)。

***步:调用this.setState

  1. ReactClass.prototype.setState = function(newState) { 
  2.     //this._reactInternalInstance是ReactCompositeComponent的实例 
  3.     this._reactInternalInstance.receiveComponent(null, newState); 
  4.  

第二步:调用内部receiveComponent方法

这里主要分三种情况,文本元素,基本元素,自定义元素。

自定义元素:

receiveComponent方法源码 

  1. // receiveComponent方法 
  2. ReactCompositeComponent.prototype.receiveComponent = function(nextElement, transaction, nextContext) { 
  3.     var prevElement = this._currentElement; 
  4.     var prevContext = this._context; 
  5.  
  6.     this._pendingElement = null
  7.  
  8.     this.updateComponent( 
  9.       transaction
  10.       prevElement, 
  11.       nextElement, 
  12.       prevContext, 
  13.       nextContext 
  14.     ); 
  15.  
  16.  

updateComponent方法源码

  1. // updateComponent方法 
  2. ReactCompositeComponent.prototype.updateComponent = function
  3.     transaction
  4.     prevParentElement, 
  5.     nextParentElement, 
  6.     prevUnmaskedContext, 
  7.     nextUnmaskedContext 
  8. ) { 
  9.    // 简写..... 
  10.     
  11.     // 不是state更新而是props更新 
  12.     if (prevParentElement !== nextParentElement) { 
  13.       willReceive = true
  14.     } 
  15.  
  16.     if (willReceive && inst.componentWillReceiveProps) { 
  17.         // 调用生命周期componentWillReceiveProps方法 
  18.     } 
  19.      
  20.     // 是否更新元素 
  21.     if (inst.shouldComponentUpdate) { 
  22.         // 如果提供shouldComponentUpdate方法 
  23.         shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); 
  24.     } else { 
  25.         if (this._compositeType === CompositeTypes.PureClass) { 
  26.           // 如果是PureClass,浅层对比props和state 
  27.           shouldUpdate = 
  28.             !shallowEqual(prevProps, nextProps) || 
  29.             !shallowEqual(inst.state, nextState); 
  30.         } 
  31.     } 
  32.      
  33.     if (shouldUpdate) { 
  34.       // 更新元素 
  35.       this._performComponentUpdate( 
  36.         nextParentElement, 
  37.         nextProps, 
  38.         nextState, 
  39.         nextContext, 
  40.         transaction
  41.         nextUnmaskedContext 
  42.       ); 
  43.     } else { 
  44.       // 不更新元素,但仍然设置props和state 
  45.       this._currentElement = nextParentElement; 
  46.       this._context = nextUnmaskedContext; 
  47.       inst.props = nextProps; 
  48.       inst.state = nextState; 
  49.       inst.context = nextContext; 
  50.     } 
  51.         
  52.    // ....... 
  53.  
  54.  

内部_performComponentUpdate方法源码

  1. function shouldUpdateReactComponent(prevElement, nextElement){ 
  2.   var prevEmpty = prevElement === null || prevElement === false
  3.   var nextEmpty = nextElement === null || nextElement === false
  4.   if (prevEmpty || nextEmpty) { 
  5.     return prevEmpty === nextEmpty; 
  6.   } 
  7.  
  8.   var prevType = typeof prevElement; 
  9.   var nextType = typeof nextElement; 
  10.    
  11.   if (prevType === 'string' || prevType === 'number') { 
  12.     // 如果先前的ReactElement对象类型是字符串或数字,新的ReactElement对象类型也是字符串或数字,则需要更新,新的ReactElement对象类型是对象,则不应该更新,直接替换。 
  13.     return (nextType === 'string' || nextType === 'number'); 
  14.   } else { 
  15.       // 如果先前的ReactElement对象类型是对象,新的ReactElement对象类型也是对象,并且标签类型和key值相同,则需要更新 
  16.     return ( 
  17.       nextType === 'object' && 
  18.       prevElement.type === nextElement.type && 
  19.       prevElement.key === nextElement.key 
  20.     ); 
  21.   } 
  22.  

文本元素:

receiveComponent方法源码

  1. ReactDOMTextComponent.prototype.receiveComponent(nextText, transaction) { 
  2.      //跟以前保存的字符串比较 
  3.     if (nextText !== this._currentElement) { 
  4.       this._currentElement = nextText; 
  5.       var nextStringText = '' + nextText; 
  6.       if (nextStringText !== this._stringText) { 
  7.         this._stringText = nextStringText; 
  8.         var commentNodes = this.getHostNode(); 
  9.         // 替换文本元素 
  10.         DOMChildrenOperations.replaceDelimitedText( 
  11.           commentNodes[0], 
  12.           commentNodes[1], 
  13.           nextStringText 
  14.         ); 
  15.       } 
  16.     } 
  17.   } 

基本元素:

receiveComponent方法源码

  1. ReactDOMComponent.prototype.receiveComponent = function(nextElement, transaction, context) { 
  2.     var prevElement = this._currentElement; 
  3.     this._currentElement = nextElement; 
  4.     this.updateComponent(transaction, prevElement, nextElement, context); 
  5.  

updateComponent方法源码

  1. ReactDOMComponent.prototype.updateComponent = function(transaction, prevElement, nextElement, context) { 
  2.     // 略..... 
  3.     //需要单独的更新属性 
  4.     this._updateDOMProperties(lastProps, nextProps, transaction, isCustomComponentTag); 
  5.     //再更新子节点 
  6.     this._updateDOMChildren( 
  7.       lastProps, 
  8.       nextProps, 
  9.       transaction
  10.       context 
  11.     ); 
  12.  
  13.     // ...... 
  14.  

this._updateDOMChildren方法内部调用diff算法,请看下一节........

react Diff算法

 diff算法源码

  1. _updateChildren: function(nextNestedChildrenElements, transaction, context) { 
  2.     var prevChildren = this._renderedChildren; 
  3.     var removedNodes = {}; 
  4.     var mountImages = []; 
  5.      
  6.     // 获取新的子元素数组 
  7.     var nextChildren = this._reconcilerUpdateChildren( 
  8.       prevChildren, 
  9.       nextNestedChildrenElements, 
  10.       mountImages, 
  11.       removedNodes, 
  12.       transaction
  13.       context 
  14.     ); 
  15.      
  16.     if (!nextChildren && !prevChildren) { 
  17.       return
  18.     } 
  19.      
  20.     var updates = null
  21.     var name
  22.     var nextIndex = 0; 
  23.     var lastIndex = 0; 
  24.     var nextMountIndex = 0; 
  25.     var lastPlacedNode = null
  26.  
  27.     for (name in nextChildren) { 
  28.       if (!nextChildren.hasOwnProperty(name)) { 
  29.         continue
  30.       } 
  31.       var prevChild = prevChildren && prevChildren[name]; 
  32.       var nextChild = nextChildren[name]; 
  33.       if (prevChild === nextChild) { 
  34.           // 同一个引用,说明是使用的同一个component,所以我们需要做移动的操作 
  35.           // 移动已有的子节点 
  36.           // NOTICE:这里根据nextIndex, lastIndex决定是否移动 
  37.         updates = enqueue( 
  38.           updates, 
  39.           this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex) 
  40.         ); 
  41.          
  42.         // 更新lastIndex 
  43.         lastIndex = Math.max(prevChild._mountIndex, lastIndex); 
  44.         // 更新component的.mountIndex属性 
  45.         prevChild._mountIndex = nextIndex; 
  46.          
  47.       } else { 
  48.         if (prevChild) { 
  49.           // 更新lastIndex 
  50.           lastIndex = Math.max(prevChild._mountIndex, lastIndex); 
  51.         } 
  52.          
  53.         // 添加新的子节点在指定的位置上 
  54.         updates = enqueue( 
  55.           updates, 
  56.           this._mountChildAtIndex( 
  57.             nextChild, 
  58.             mountImages[nextMountIndex], 
  59.             lastPlacedNode, 
  60.             nextIndex, 
  61.             transaction
  62.             context 
  63.           ) 
  64.         ); 
  65.          
  66.          
  67.         nextMountIndex++; 
  68.       } 
  69.        
  70.       // 更新nextIndex 
  71.       nextIndex++; 
  72.       lastPlacedNode = ReactReconciler.getHostNode(nextChild); 
  73.     } 
  74.      
  75.     // 移除掉不存在的旧子节点,和旧子节点和新子节点不同的旧子节点 
  76.     for (name in removedNodes) { 
  77.       if (removedNodes.hasOwnProperty(name)) { 
  78.         updates = enqueue( 
  79.           updates, 
  80.           this._unmountChild(prevChildren[name], removedNodes[name]) 
  81.         ); 
  82.       } 
  83.     } 
  84.   }  

react的优点与总结

优点

  • 虚拟节点。在UI方面,不需要立刻更新视图,而是生成虚拟DOM后统一渲染。
  • 组件机制。各个组件独立管理,层层嵌套,互不影响,react内部实现的渲染功能。
  • 差异算法。根据基本元素的key值,判断是否递归更新子节点,还是删除旧节点,添加新节点。

总结

想要更好的利用react的虚拟DOM,diff算法的优势,我们需要正确的优化、组织react页面。例如将一个页面render的ReactElement节点分解成多个组件。在需要优化的组件手动添加 shouldComponentUpdate 来避免不需要的 re-render。

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2015-03-17 09:44:08

2018-07-09 15:11:14

Java逃逸JVM

2016-12-08 15:36:59

HashMap数据结构hash函数

2020-07-21 08:26:08

SpringSecurity过滤器

2010-06-01 15:25:27

JavaCLASSPATH

2024-01-29 15:54:41

Java线程池公平锁

2021-10-15 09:19:17

AndroidSharedPrefe分析源码

2021-09-08 06:51:52

AndroidRetrofit原理

2017-01-10 08:48:21

2020-09-23 10:00:26

Redis数据库命令

2017-08-15 13:05:58

Serverless架构开发运维

2024-02-21 21:14:20

编程语言开发Golang

2019-06-25 10:32:19

UDP编程通信

2013-09-22 14:57:19

AtWood

2023-10-19 11:12:15

Netty代码

2009-09-25 09:14:35

Hibernate日志

2021-02-17 11:25:33

前端JavaScriptthis

2021-08-24 07:53:28

AndroidActivity生命周期

2022-11-11 10:48:55

AQS源码架构

2012-11-22 13:02:24

jQuery插件Web
点赞
收藏

51CTO技术栈公众号