從 0 到 1 實現 React 系列 —— 生命週期和 diff 算法

本系列文章在實現一個 (x)react 的同時理順 React 框架的主幹內容(JSX/虛擬DOM/組件/生命週期/diff算法/...)html

生命週期

先來回顧 React 的生命週期,用流程圖表示以下:node

該流程圖比較清晰地呈現了 react 的生命週期。其分爲 3 個階段 —— 生成期,存在期,銷燬期。react

由於生命週期鉤子函數存在於自定義組件中,將以前 _render 函數做些調整以下:git

// 原來的 _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 函數內(渲染前)加入 componentWillMountcomponentWillReceiveProps 方法,setProps 函數以下:github

function setProps(component) {
  if (component && component.componentWillMount) {
    component.componentWillMount()
  } else if (component.base && component.componentWillReceiveProps) {
    component.componentWillReceiveProps(component.props) // 後面待實現
  }
}

然後咱們在 renderComponent 函數內加入 componentDidMountshouldComponentUpdatecomponentWillUpdatecomponentDidUpdate 方法算法

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')
)

頁面加載時輸出結果以下:app

componentWillMount
render
componentDidMount

點擊按鈕時輸出結果以下:框架

shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

diff 的實現

在 react 中,diff 實現的思路是將新老 virtual dom 進行比較,將比較後的 patch(補丁)渲染到頁面上,從而實現局部刷新;本文借鑑了 preactsimple-react 中的 diff 實現,整體思路是將舊的 dom 節點和新的 virtual dom 節點進行了比較,根據不一樣的比較類型(文本節點、非文本節點、自定義組件)調用相應的邏輯,從而實現頁面的局部渲染。代碼整體結構以下: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 測試

項目地址關於如何 pr

相關文章
相關標籤/搜索