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 如此厉害的框架,除了优秀的架构和出色的算法,其实也离不开这些普普统统的很好理解的代码。
相关文章
相关标签/搜索