从 0 到 1 实现 React 系列 —— 3.生命周期和 diff 算法
看源码一个痛处是会陷进理不顺主干的困局中,本系列文章在实现一个 (x)react 的同时理顺 React 框架的主干内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/ref/...)
- 从 0 到 1 实现 React 系列 —— JSX 和 Virtual DOM
- 从 0 到 1 实现 React 系列 —— 组件和 state|props
- 从 0 到 1 实现 React 系列 —— 生命周期和 diff 算法
- 从 0 到 1 实现 React 系列 —— 优化 setState 和 ref 的实现
生命周期
先来回顾 React 的生命周期,用流程图表示如下:

该流程图比较清晰地呈现了 react 的生命周期。其分为 3 个阶段 —— 生成期,存在期,销毁期。
因为生命周期钩子函数存在于自定义组件中,将之前 _render 函数作些调整如下:
// 原来的 _render 函数,为了将职责拆分得更细,将 virtual dom 转为 real dom 的函数单独抽离出来
function vdomToDom(vdom) {
if (_.isFunction(vdom.nodeName)) { // 为了更加方便地书写生命周期逻辑,将解析自定义组件逻辑和一般 html 标签的逻辑分离开
const component = createComponent(vdom) // 构造组件
setProps(component) // 更改组件 props
renderComponent(component) // 渲染组件,将 dom 节点赋值到 component
return component.base // 返回真实 dom
}
...
}
我们可以在 setProps 函数内(渲染前)加入 componentWillMount,componentWillReceiveProps 方法,setProps 函数如下:
function setProps(component) {
if (component && component.componentWillMount) {
component.componentWillMount()
} else if (component.base && component.componentWillReceiveProps) {
component.componentWillReceiveProps(component.props) // 后面待实现
}
}
而后我们在 renderComponent 函数内加入 componentDidMount、shouldComponentUpdate、componentWillUpdate、componentDidUpdate 方法
function renderComponent(component) {
if (component.base && component.shouldComponentUpdate) {
const bool = component.shouldComponentUpdate(component.props, component.state)
if (!bool && bool !== undefined) {
return false // shouldComponentUpdate() 返回 false,则生命周期终止
}
}
if (component.base && component.componentWillUpdate) {
component.componentWillUpdate()
}
const rendered = component.render()
const base = vdomToDom(rendered)
if (component.base && component.componentDidUpdate) {
component.componentDidUpdate()
} else if (component && component.componentDidMount) {
component.componentDidMount()
}
if (component.base && component.base.parentNode) { // setState 进入此逻辑
component.base.parentNode.replaceChild(base, component.base)
}
component.base = base // 标志符
}
测试生命周期
测试如下用例:
class A extends Component {
componentWillReceiveProps(props) {
console.log('componentWillReceiveProps')
}
render() {
return (
<div>{this.props.count}</div>
)
}
}
class B extends Component {
constructor(props) {
super(props)
this.state = {
count: 1
}
}
componentWillMount() {
console.log('componentWillMount')
}
componentDidMount() {
console.log('componentDidMount')
}
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate', nextProps, nextState)
return true
}
componentWillUpdate() {
console.log('componentWillUpdate')
}
componentDidUpdate() {
console.log('componentDidUpdate')
}
click() {
this.setState({
count: ++this.state.count
})
}
render() {
console.log('render')
return (
<div>
<button onClick={this.click.bind(this)}>Click Me!</button>
<A count={this.state.count} />
</div>
)
}
}
ReactDOM.render(
<B />,
document.getElementById('root')
)
页面加载时输出结果如下:
componentWillMount
render
componentDidMount
点击按钮时输出结果如下:
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
diff 的实现
在 react 中,diff 实现的思路是将新老 virtual dom 进行比较,将比较后的 patch(补丁)渲染到页面上,从而实现局部刷新;本文借鉴了 preact 和 simple-react 中的 diff 实现,总体思路是将旧的 dom 节点和新的 virtual dom 节点进行了比较,根据不同的比较类型(文本节点、非文本节点、自定义组件)调用相应的逻辑,从而实现页面的局部渲染。代码总体结构如下:
/**
* 比较旧的 dom 节点和新的 virtual dom 节点:
* @param {*} oldDom 旧的 dom 节点
* @param {*} newVdom 新的 virtual dom 节点
*/
function diff(oldDom, newVdom) {
...
if (_.isString(newVdom)) {
return diffTextDom(oldDom, newVdom) // 对比文本 dom 节点
}
if (oldDom.nodeName.toLowerCase() !== newVdom.nodeName) {
diffNotTextDom(oldDom, newVdom) // 对比非文本 dom 节点
}
if (_.isFunction(newVdom.nodeName)) {
return diffComponent(oldDom, newVdom) // 对比自定义组件
}
diffAttribute(oldDom, newVdom) // 对比属性
if (newVdom.children.length > 0) {
diffChild(oldDom, newVdom) // 遍历对比子节点
}
return oldDom
}
下面根据不同比较类型实现相应逻辑。
对比文本节点
首先进行较为简单的文本节点的比较,代码如下:
// 对比文本节点
function diffTextDom(oldDom, newVdom) {
let dom = oldDom
if (oldDom && oldDom.nodeType === 3) { // 如果老节点是文本节点
if (oldDom.textContent !== newVdom) { // 这里一个细节:textContent/innerHTML/innerText 的区别
oldDom.textContent = newVdom
}
} else { // 如果旧 dom 元素不为文本节点
dom = document.createTextNode(newVdom)
if (oldDom && oldDom.parentNode) {
oldDom.parentNode.replaceChild(dom, oldDom)
}
}
return dom
}
对比非文本节点
对比非文本节点,其思路为将同层级的旧节点替换为新节点,代码如下:
// 对比非文本节点
function diffNotTextDom(oldDom, newVdom) {
const newDom = document.createElement(newVdom.nodeName);
[...oldDom.childNodes].map(newDom.appendChild) // 将旧节点下的元素添加到新节点下
if (oldDom && oldDom.parentNode) {
oldDom.parentNode.replaceChild(oldDom, newDom)
}
}
对比自定义组件
对比自定义组件的思路为:如果新老组件不同,则直接将新组件替换老组件;如果新老组件相同,则将新组件的 props 赋到老组件上,然后再对获得新 props 前后的老组件做 diff 比较。代码如下:
// 对比自定义组件
function diffComponent(oldDom, newVdom) {
if (oldDom._component && (oldDom._component.constructor !== newVdom.nodeName)) { // 如果新老组件不同,则直接将新组件替换老组件
const newDom = vdomToDom(newVdom)
oldDom._component.parentNode.insertBefore(newDom, oldDom._component)
oldDom._component.parentNode.removeChild(oldDom._component)
} else {
setProps(oldDom._component, newVdom.attributes) // 如果新老组件相同,则将新组件的 props 赋到老组件上
renderComponent(oldDom._component) // 对获得新 props 前后的老组件做 diff 比较(renderComponent 中调用了 diff)
}
}
遍历对比子节点
遍历对比子节点的策略有两个:一是只比较同层级的节点,二是给节点加上 key 属性。它们的目的都是降低空间复杂度。代码如下:
// 对比子节点
function diffChild(oldDom, newVdom) {
const keyed = {}
const children = []
const oldChildNodes = oldDom.childNodes
for (let i = 0; i < oldChildNodes.length; i++) {
if (oldChildNodes[i].key) { // 将含有 key 的节点存进对象 keyed
keyed[oldChildNodes[i].key] = oldChildNodes[i]
} else { // 将不含有 key 的节点存进数组 children
children.push(oldChildNodes[i])
}
}
const newChildNodes = newVdom.children
let child
for (let i = 0; i < newChildNodes.length; i++) {
if (keyed[newChildNodes[i].key]) { // 对应上面存在 key 的情形
child = keyed[newChildNodes[i].key]
keyed[newChildNodes[i].key] = undefined
} else { // 对应上面不存在 key 的情形
for (let j = 0; j < children.length; j++) {
if (isSameNodeType(children[i], newChildNodes[i])) { // 如果不存在 key,则优先找到节点类型相同的元素
child = children[i]
children[i] = undefined
break
}
}
}
diff(child, newChildNodes[i]) // 递归比较
}
}
测试
在生命周期的小节中,componentWillReceiveProps 方法还未跑通,稍加修改 setProps 函数即可:
/**
* 更改属性,componentWillMount 和 componentWillReceiveProps 方法
*/
function setProps(component, attributes) {
if (attributes) {
component.props = attributes // 这段逻辑对应上文自定义组件比较中新老组件相同时 setProps 的逻辑
}
if (component && component.base && component.componentWillReceiveProps) {
component.componentWillReceiveProps(component.props)
} else if (component && component.componentWillMount) {
component.componentWillMount()
}
}
来测试下生命周期小节中最后的测试用例:
- 生命周期测试

- diff 测试

从 0 到 1 实现 React 系列 —— 3.生命周期和 diff 算法的更多相关文章
- 从 0 到 1 实现 React 系列 —— 1.JSX 和 Virtual DOM
看源码一个痛处是会陷进理不顺主干的困局中,本系列文章在实现一个 (x)react 的同时理顺 React 框架的主干内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/ref/. ...
- 从 0 到 1 实现 React 系列 —— 5.PureComponent 实现 && HOC 探幽
本系列文章在实现一个 cpreact 的同时帮助大家理顺 React 框架的核心内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/PureComponent/HOC/...) ...
- 从 0 到 1 实现 React 系列 —— 4.setState优化和ref的实现
看源码一个痛处是会陷进理不顺主干的困局中,本系列文章在实现一个 (x)react 的同时理顺 React 框架的主干内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/ref/. ...
- 从 0 到 1 实现 React 系列 —— 2.组件和 state|props
看源码一个痛处是会陷进理不顺主干的困局中,本系列文章在实现一个 (x)react 的同时理顺 React 框架的主干内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/ref/. ...
- React源码剖析系列 - 生命周期的管理艺术
目前,前端领域中 React 势头正盛,很少能够深入剖析内部实现机制和原理.本系列文章希望通过剖析 React 源码,理解其内部的实现原理,知其然更要知其所以然. 对于 React,其组件生命周期(C ...
- React 源码剖析系列 - 生命周期的管理艺术
目前,前端领域中 React 势头正盛,很少能够深入剖析内部实现机制和原理. 本系列文章 希望通过剖析 React 源码,理解其内部的实现原理,知其然更要知其所以然. 对于 React,其组件生命周期 ...
- 07、NetCore2.0依赖注入(DI)之生命周期
07.NetCore2.0依赖注入(DI)之生命周期 NetCore2.0依赖注入框架(DI)是如何管理注入对象的生命周期的?生命周期有哪几类,又是在哪些场景下应用的呢? -------------- ...
- React组件和生命周期简介
React 简介----React 是 Facebook 出品的一套颠覆式的前端开发类库.为什么说它是颠覆式的呢? 内存维护虚拟 DOM 对于传统的 DOM 维护,我们的步骤可能是:1.初始化 ...
- React 之 组件生命周期
React 之 组件生命周期 理解1) 组件对象从创建到死亡它会经历特定的生命周期阶段2) React组件对象包含一系列的勾子函数(生命周期回调函数), 在生命周期特定时刻回调3) 我们在定义组件时, ...
随机推荐
- JAVA项目从运维部署到项目开发(一.Jenkins)
一.Jenkins的介绍 Jenkins是一个开源软件项目,是基于Java开发的一种持续集成工具,用于监控持续重复的工作, 旨在提供一个开放易用的软件平台,使软件的持续集成变成可能. 二.功能 Jen ...
- Android 官方DEMO BasicNetworking
本示例演示如何使用Android API检查网络连接. Demo下载地址:https://github.com/googlesamples/android-BasicNetworking/#readm ...
- Linux中对逻辑卷的建立
大体上与主分区的建立相同,只有一些不同. 建议大家先看下我的“Linux中安装硬盘后对硬盘的分区以及挂载” https://www.cnblogs.com/feiquan/p/9219447.htm ...
- telnet 测试网站是否开启长连接
测试服务器是否开启keepalive(长连接) telnet 主机名(域名|IP) 80 #发起请求GET /index.html HTTP/1.1Host: www.cbnsc.com 如果请求完后 ...
- ORACLE中内部函数SYS_OP_C2C和隐式类型转换
什么是SYS_OP_C2C呢?官方的介绍如下: SYS_OP_C2C is an internal function which does an implicit conversion of varc ...
- Spring MVC HelloWorld入门及运行机制 (一)
完整的项目案例: springmvc.zip 介绍 SpringMVC是一款Web MVC框架. 它跟Struts框架类似,是目前主流的Web MVC框架之一. 文章通过实例来介绍SpringMVC的 ...
- java验证码的制作和验证
验证码作用: 没有验证码登陆,黑客会更加容易破解你的账号,通过组合码刷机等黑客技术来破取你的密码,有了验证码相当于加了一层很厚的屏障,安全系数很高. 验证码是一种区分用户是计算机和人的公共全自动程序. ...
- CentOS 6.5 安装mysql 过程记录
下载的时候一定选对应的版本, el6 还是el7 或者其他版本,不然会出现意向不到的惊喜 比如:我刚开始的时候下载的 el7 版本的 mysql , 然后安装的时候 就会出现: libc.so.(GL ...
- hive笔记:转义字符的使用
hive中的转义符 Hadoop和Hive都是用UTF-8编码的,所以, 所有中文必须是UTF-8编码, 才能正常使用 备注:中文数据load到表里面, 如果字符集不同,很有可能全是乱码需要做转码的, ...
- c/c++ 多态的实现原理分析
多态的实现原理分析 当类里有一个函数被声明成虚函数后,创建这个类的对象的时候,就会自动加入一个__vfptr的指针, __vfptr维护虚函数列表.如果有三个虚函数,则__vfptr指向的是第一个虚函 ...