从 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) 我们在定义组件时, ...
随机推荐
- Windows Server 2016-Active Directory复制概念(一)
停更十余天后,从今天开始继续为大家带来Windows Server 2016 Active Directory系列更新,本章为大家介绍有关Active Directory复制相关概念内容,有关Acti ...
- Windows 系统下 mysql workbench 的安装及环境配置
1.MySQL的官网地址:https://www.mysql.com/ 2,选择DOWNLOADS 3.选择community 再MySQL workbench 4.安装MySQL workbench ...
- MyBatis:参数传递 [转]
一.单个参数: public List<XXBean> getXXBeanList(String xxCode); <select id="getXXXBeanList&q ...
- PHP的move_uploaded_file()出错解决
今天用的PHP的move_uploaded_file方法保存前端上传的中文名称文件时,方法返回假,调试时错误码为2,错误信息为: move_uploaded_file(D:\ git_prj \ xx ...
- elixir mix 简介
概述 mix 是 elixir 工程的构建工具,利用 mix,可以快速方便的创建 elixir 工程,写单元测试,管理 elixir 包的依赖管理等等. 我觉得刚开始学习 elixir 的时候,先简单 ...
- Linux 小知识翻译 - 「BitTorrent」
这次聊聊「BitTorrent」. (也就是下片子的 BT) BitTorrent是文件传输的一种.它可以在服务端负担很小的情况下高速的传输文件. BitTorrent最大的特点就是服务端可以将文件的 ...
- 《数据库技术基础与应用(第2版)》学习笔记——第7章~
从这章开始,操作的内容开始增多,概念的东西越来越少,可能跟学校的教学目的有关,但是跟我的学习目的不匹配,就不再继续整理. 总结:这本书适合大学本科生学习和了解数据库的相关知识以及Access和SQL ...
- Linux之文档与目录结构
Linux文件系统结构 Linux目录结构的组织形式和Windows有很大的不同.首先Linux没有“盘(C盘.D盘.E盘)”的概念.已经建立文件系统的硬盘分区被挂载到某一个目录下,用户通过操作目录来 ...
- python 基本运算符
一.格式化输出 简易名片的制作 name="小龙女" phone=15464623646 firm="神雕侠侣" pro="神仙姐姐" pr ...
- docker学习笔记(三)-通过network理解docker,在同一网桥里搭建docker容器
创建test1 test2 两个network namespace 两个network namespace没有被启动 启动了但是有没有与network关联 创建两个veth,用于关联两个network ...