前情提要
React小知识(1) - 这个defaultProps可以删掉吗?
干货
上一篇最后总结到,需要理解一下defaultProps是如何实现。
趁着下班时间,赶紧找了一下源码地址
首先我们回顾一下 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
实际执行了什么方法。
经过断点调试,我们可以清晰的看到
代码从
ReactDOM.render(<App />, document.getElementById('root'))
到
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
如此厉害的框架,除了优秀的架构和出色的算法,其实也离不开这些普普通通的很好理解的代码。