Home  >  Article  >  Web Front-end  >  Implementing the React series from 0 to 1: implementation of life cycle and diff

Implementing the React series from 0 to 1: implementation of life cycle and diff

php是最好的语言
php是最好的语言Original
2018-07-27 14:22:241244browse

Implementing the React series from 0 to 1: implementation of life cycle and diff

This series of articles implements a (x)react while straightening out the backbone content of the React framework (JSX/virtual DOM/component/life cycle/diff algorithm/...)

  • Implementing the React series from 0 to 1 - JSX and Virtual DOM

  • Implementing the React series from 0 to 1 - components and state|props

Life cycle

Let’s first review the life cycle of React, which is represented by a flow chart as follows:

Implementing the React series from 0 to 1: implementation of life cycle and diff

The The flow chart presents the life cycle of react relatively clearly. It is divided into 3 stages - generation period, existence period and destruction period.

Because the life cycle hook function exists in the custom component, make some adjustments to the previous _render function as follows:

// 原来的 _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
  }
  ...
}

We can add componentWillMount within the setProps function (before rendering) , componentWillReceiveProps method, setProps function is as follows:

function setProps(component) {
  if (component && component.componentWillMount) {
    component.componentWillMount()
  } else if (component.base && component.componentWillReceiveProps) {
    component.componentWillReceiveProps(component.props) // 后面待实现
  }
}

Then we add componentDidMount, shouldComponentUpdate, in the renderComponent function componentWillUpdate, componentDidUpdate Method

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  // 标志符
}

Test life cycle

Test the following use case:

class A extends Component {
  componentWillReceiveProps(props) {
    console.log('componentWillReceiveProps')
  }

  render() {
    return (
      <p>{this.props.count}</p>
    )
  }
}

class B extends Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 1
    }
  }

  componentWillMount() {
    console.log(&#39;componentWillMount&#39;)
  }

  componentDidMount() {
    console.log(&#39;componentDidMount&#39;)
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log(&#39;shouldComponentUpdate&#39;, nextProps, nextState)
    return true
  }

  componentWillUpdate() {
    console.log(&#39;componentWillUpdate&#39;)
  }

  componentDidUpdate() {
    console.log(&#39;componentDidUpdate&#39;)
  }

  click() {
    this.setState({
      count: ++this.state.count
    })
  }

  render() {
    console.log(&#39;render&#39;)
    return (
      <p>
        <button onClick={this.click.bind(this)}>Click Me!</button>
        <A count={this.state.count} />
      </p>
    )
  }
}

ReactDOM.render(
  <B />,
  document.getElementById(&#39;root&#39;)
)

The output result when the page is loaded is as follows:

componentWillMount
render
componentDidMount

The output result when clicking the button is as follows:

shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

Implementation of diff

In react, the idea of ​​​​diff implementation is to compare the old and new virtual dom, and compare the patch ( Patch) is rendered to the page to achieve partial refresh; this article draws on the diff implementation in preact and simple-react. The general idea is to compare the old dom node and the new virtual dom node. According to different comparison types (text nodes, non-text nodes, custom components) to call the corresponding logic to achieve partial rendering of the page. The overall structure of the code is as follows:

/**
 * 比较旧的 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
}

The following implements the corresponding logic according to different comparison types.

Compare text nodes

First compare simple text nodes, the code is as follows:

// 对比文本节点
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
}

Compare non-text nodes

Compare non-text nodes, The idea is to replace old nodes at the same level with new nodes. The code is as follows:

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

Compare custom components

The idea of ​​comparing custom components is: If the old and new components are different, directly Replace the old component with the new component; if the old and new components are the same, assign the props of the new component to the old component, and then do a diff comparison of the old components before and after obtaining the new props. The code is as follows:

// 对比自定义组件
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)
  }
}

Traverse and compare child nodes

There are two strategies for traversing and comparing child nodes: one is to only compare nodes at the same level, and the other is to add key attributes to nodes. Their purpose is to reduce space complexity. The code is as follows:

// 对比子节点
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]) // 递归比较
  }
}

Test

In the life cycle section, the componentWillReceiveProps method has not yet run through. Just modify the setProps function slightly:

/**
 * 更改属性,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()
  }
}

To test the life The last test case in the cycle section:

  • Life cycle test

Implementing the React series from 0 to 1: implementation of life cycle and diff

  • ## diff test

Implementing the React series from 0 to 1: implementation of life cycle and diff

Project address, about how to pr

Related articles:

React component life Cycle instance analysis

Detailed explanation of React component life cycle

Related videos:

Virtual dom-React framework video tutorial

The above is the detailed content of Implementing the React series from 0 to 1: implementation of life cycle and diff. 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