本系列文章在实现一个 (x)react 的同时理顺 React 框架的主干内容(JSX/虚拟DOM/组件/生命周期/diff算法/…)

先来回顾 React 的生命周期,用流程图表示如下:

该流程图比较清晰地呈现了 react 的生命周期。其分为 3 个阶段 —— 生成期,存在期,销毁期。

因为生命周期钩子函数存在于自定义组件中,将之前 _render 函数作些调整如下:

  1. // 原来的 _render 函数,为了将职责拆分得更细,将 virtual dom 转为 real dom 的函数单独抽离出来
  2. function vdomToDom(vdom) {
  3. if (_.isFunction(vdom.nodeName)) { // 为了更加方便地书写生命周期逻辑,将解析自定义组件逻辑和一般 html 标签的逻辑分离开
  4. const component = createComponent(vdom) // 构造组件
  5. setProps(component) // 更改组件 props
  6. renderComponent(component) // 渲染组件,将 dom 节点赋值到 component
  7. return component.base // 返回真实 dom
  8. }
  9. ...
  10. }

我们可以在 setProps 函数内(渲染前)加入 componentWillMountcomponentWillReceiveProps 方法,setProps 函数如下:

  1. function setProps(component) {
  2. if (component && component.componentWillMount) {
  3. component.componentWillMount()
  4. } else if (component.base && component.componentWillReceiveProps) {
  5. component.componentWillReceiveProps(component.props) // 后面待实现
  6. }
  7. }

而后我们在 renderComponent 函数内加入 componentDidMountshouldComponentUpdatecomponentWillUpdatecomponentDidUpdate 方法

  1. function renderComponent(component) {
  2. if (component.base && component.shouldComponentUpdate) {
  3. const bool = component.shouldComponentUpdate(component.props, component.state)
  4. if (!bool && bool !== undefined) {
  5. return false // shouldComponentUpdate() 返回 false,则生命周期终止
  6. }
  7. }
  8. if (component.base && component.componentWillUpdate) {
  9. component.componentWillUpdate()
  10. }
  11. const rendered = component.render()
  12. const base = vdomToDom(rendered)
  13. if (component.base && component.componentDidUpdate) {
  14. component.componentDidUpdate()
  15. } else if (component && component.componentDidMount) {
  16. component.componentDidMount()
  17. }
  18. if (component.base && component.base.parentNode) { // setState 进入此逻辑
  19. component.base.parentNode.replaceChild(base, component.base)
  20. }
  21. component.base = base // 标志符
  22. }

测试如下用例:

  1. class A extends Component {
  2. componentWillReceiveProps(props) {
  3. console.log('componentWillReceiveProps')
  4. }
  5. render() {
  6. return (
  7. <div>{this.props.count}</div>
  8. )
  9. }
  10. }
  11. class B extends Component {
  12. constructor(props) {
  13. super(props)
  14. this.state = {
  15. count: 1
  16. }
  17. }
  18. componentWillMount() {
  19. console.log('componentWillMount')
  20. }
  21. componentDidMount() {
  22. console.log('componentDidMount')
  23. }
  24. shouldComponentUpdate(nextProps, nextState) {
  25. console.log('shouldComponentUpdate', nextProps, nextState)
  26. return true
  27. }
  28. componentWillUpdate() {
  29. console.log('componentWillUpdate')
  30. }
  31. componentDidUpdate() {
  32. console.log('componentDidUpdate')
  33. }
  34. click() {
  35. this.setState({
  36. count: ++this.state.count
  37. })
  38. }
  39. render() {
  40. console.log('render')
  41. return (
  42. <div>
  43. <button onClick={this.click.bind(this)}>Click Me!</button>
  44. <A count={this.state.count} />
  45. </div>
  46. )
  47. }
  48. }
  49. ReactDOM.render(
  50. <B />,
  51. document.getElementById('root')
  52. )

页面加载时输出结果如下:

  1. componentWillMount
  2. render
  3. componentDidMount

点击按钮时输出结果如下:

  1. shouldComponentUpdate
  2. componentWillUpdate
  3. render
  4. componentDidUpdate

在 react 中,diff 实现的思路是将新老 virtual dom 进行比较,将比较后的 patch(补丁)渲染到页面上,从而实现局部刷新;本文借鉴了 preactsimple-react 中的 diff 实现,总体思路是将旧的 dom 节点和新的 virtual dom 节点进行了比较,根据不同的比较类型(文本节点、非文本节点、自定义组件)调用相应的逻辑,从而实现页面的局部渲染。代码总体结构如下:

  1. /**
  2. * 比较旧的 dom 节点和新的 virtual dom 节点:
  3. * @param {*} oldDom 旧的 dom 节点
  4. * @param {*} newVdom 新的 virtual dom 节点
  5. */
  6. function diff(oldDom, newVdom) {
  7. ...
  8. if (_.isString(newVdom)) {
  9. return diffTextDom(oldDom, newVdom) // 对比文本 dom 节点
  10. }
  11. if (oldDom.nodeName.toLowerCase() !== newVdom.nodeName) {
  12. diffNotTextDom(oldDom, newVdom) // 对比非文本 dom 节点
  13. }
  14. if (_.isFunction(newVdom.nodeName)) {
  15. return diffComponent(oldDom, newVdom) // 对比自定义组件
  16. }
  17. diffAttribute(oldDom, newVdom) // 对比属性
  18. if (newVdom.children.length > 0) {
  19. diffChild(oldDom, newVdom) // 遍历对比子节点
  20. }
  21. return oldDom
  22. }

下面根据不同比较类型实现相应逻辑。

首先进行较为简单的文本节点的比较,代码如下:

  1. // 对比文本节点
  2. function diffTextDom(oldDom, newVdom) {
  3. let dom = oldDom
  4. if (oldDom && oldDom.nodeType === 3) { // 如果老节点是文本节点
  5. if (oldDom.textContent !== newVdom) { // 这里一个细节:textContent/innerHTML/innerText 的区别
  6. oldDom.textContent = newVdom
  7. }
  8. } else { // 如果旧 dom 元素不为文本节点
  9. dom = document.createTextNode(newVdom)
  10. if (oldDom && oldDom.parentNode) {
  11. oldDom.parentNode.replaceChild(dom, oldDom)
  12. }
  13. }
  14. return dom
  15. }

对比非文本节点,其思路为将同层级的旧节点替换为新节点,代码如下:

  1. // 对比非文本节点
  2. function diffNotTextDom(oldDom, newVdom) {
  3. const newDom = document.createElement(newVdom.nodeName);
  4. [...oldDom.childNodes].map(newDom.appendChild) // 将旧节点下的元素添加到新节点下
  5. if (oldDom && oldDom.parentNode) {
  6. oldDom.parentNode.replaceChild(oldDom, newDom)
  7. }
  8. }

对比自定义组件的思路为:如果新老组件不同,则直接将新组件替换老组件;如果新老组件相同,则将新组件的 props 赋到老组件上,然后再对获得新 props 前后的老组件做 diff 比较。代码如下:

  1. // 对比自定义组件
  2. function diffComponent(oldDom, newVdom) {
  3. if (oldDom._component && (oldDom._component.constructor !== newVdom.nodeName)) { // 如果新老组件不同,则直接将新组件替换老组件
  4. const newDom = vdomToDom(newVdom)
  5. oldDom._component.parentNode.insertBefore(newDom, oldDom._component)
  6. oldDom._component.parentNode.removeChild(oldDom._component)
  7. } else {
  8. setProps(oldDom._component, newVdom.attributes) // 如果新老组件相同,则将新组件的 props 赋到老组件上
  9. renderComponent(oldDom._component) // 对获得新 props 前后的老组件做 diff 比较(renderComponent 中调用了 diff)
  10. }
  11. }

遍历对比子节点的策略有两个:一是只比较同层级的节点,二是给节点加上 key 属性。它们的目的都是降低空间复杂度。代码如下:

  1. // 对比子节点
  2. function diffChild(oldDom, newVdom) {
  3. const keyed = {}
  4. const children = []
  5. const oldChildNodes = oldDom.childNodes
  6. for (let i = 0; i < oldChildNodes.length; i++) {
  7. if (oldChildNodes[i].key) { // 将含有 key 的节点存进对象 keyed
  8. keyed[oldChildNodes[i].key] = oldChildNodes[i]
  9. } else { // 将不含有 key 的节点存进数组 children
  10. children.push(oldChildNodes[i])
  11. }
  12. }
  13. const newChildNodes = newVdom.children
  14. let child
  15. for (let i = 0; i < newChildNodes.length; i++) {
  16. if (keyed[newChildNodes[i].key]) { // 对应上面存在 key 的情形
  17. child = keyed[newChildNodes[i].key]
  18. keyed[newChildNodes[i].key] = undefined
  19. } else { // 对应上面不存在 key 的情形
  20. for (let j = 0; j < children.length; j++) {
  21. if (isSameNodeType(children[i], newChildNodes[i])) { // 如果不存在 key,则优先找到节点类型相同的元素
  22. child = children[i]
  23. children[i] = undefined
  24. break
  25. }
  26. }
  27. }
  28. diff(child, newChildNodes[i]) // 递归比较
  29. }
  30. }

在生命周期的小节中,componentWillReceiveProps 方法还未跑通,稍加修改 setProps 函数即可:

  1. /**
  2. * 更改属性,componentWillMount 和 componentWillReceiveProps 方法
  3. */
  4. function setProps(component, attributes) {
  5. if (attributes) {
  6. component.props = attributes // 这段逻辑对应上文自定义组件比较中新老组件相同时 setProps 的逻辑
  7. }
  8. if (component && component.base && component.componentWillReceiveProps) {
  9. component.componentWillReceiveProps(component.props)
  10. } else if (component && component.componentWillMount) {
  11. component.componentWillMount()
  12. }
  13. }

来测试下生命周期小节中最后的测试用例:

  • 生命周期测试

  • diff 测试

项目地址关于如何 pr

版权声明:本文为MuYunyun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/MuYunyun/p/9375560.html