React小知識(2) - defaultProps的實現

前情提要

React小知識(1) - 這個defaultProps能夠刪掉嗎?react

乾貨

上一篇最後總結到,須要理解一下defaultProps是如何實現。git

趁着下班時間,趕忙找了一下源碼地址github

首先咱們回顧一下 defaultProps 的用法算法

import React from 'react';

class App extends React.Component {
  render() {
    return <div>{this.props.name}</div>
  }
}

App.defaultProps = {
  name: "Hello React"
};

ReactDOM.render(<App />, document.getElementById('root'));
複製代碼

這樣咱們就能夠獲得一個渲染出Hello React的界面啦。架構

此時的關鍵,在於須要理解 ReactDOM.render 實際執行了什麼方法。框架

通過斷點調試,咱們能夠清晰的看到post

代碼從性能

ReactDOM.render(<App />, document.getElementById('root'))this

spa

React.createElmentWithValidation(type, props, children)

因爲 createElementWithValidation 並非我想了解的重點,簡要看了一下,大概執行了如下3步。

  • 判斷第一個參數(示例代碼中的 <App /> 是不是有效元素 ), 若是不正確,你就會看到 React.createElement: type is invalid , 這個熟悉又親切的報錯

  • 執行 React.createElement(type, props, children)

  • 檢查元素的 props 是否符合 propTypes 的約定

其中對咱們理解defaultProps有幫助的是第2步,React.createElement

咱們能夠看到在源碼地址的第221行中,寫着清晰的註釋 Resolve default props

// Resolve default props
if (type && type.defaultProps) {
  const defaultProps = type.defaultProps;
  for (propName in defaultProps) {
    if (props[propName] === undefined) {
      props[propName] = defaultProps[propName];
    }
  }
}
複製代碼

經過剛纔的分析,咱們能夠知道上文代碼中的 type 正是 App 對象。因此這裏對 type.defaultProps 使用,就豁然開朗了。

根據這段代碼,咱們更加能夠印證,上一篇文章中提到多餘的 defaultProps 確實會對代碼的性能形成影響。

由於當 type.defaultProps 存在時,是須要對其進行遍歷的。

因此若是你的文件中存在不少處這種無效的代碼,雖然並不會對界面產生任何影響,可是確實影響了代碼的質量。

總結

  • 勿以善小而不爲,勿以惡小而爲之。注意本身的實現細節,提升代碼質量。
  • React 如此厲害的框架,除了優秀的架構和出色的算法,其實也離不開這些普普統統的很好理解的代碼。
相關文章
相關標籤/搜索