React PureComponent 源码解析
TL;DRReact 15.3.0 新增了一个 PureComponent 源码分析这个类的用法很简单,如果你有些组件是纯组件,那么把继承类从 import React,{ PureComponent } from 'react' class Example extends PureComponent { render() { // ... } }
function ReactPureComponent(props,context,updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. Object.assign(ReactPureComponent.prototype,ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; 上面的 跟
这个类的代码改动很多,但关键就在 这里 。下面是我简化后的代码片段: // 定义 CompositeTypes var CompositeTypes = { ImpureClass: 0,// 继承自 Component 的组件 PureClass: 1,// 继承自 PureComponent 的组件 StatelessFunctional: 2,// 函数组件 }; // 省略一堆代码,因为加入了 CompositeTypes 造成的调整 // 这个变量用来控制组件是否需要更新 var shouldUpdate = true; // inst 是组件实例 if (inst.shouldComponentUpdate) { shouldUpdate = inst.shouldComponentUpdate(nextProps,nextState,nextContext); } else { if (this._compositeType === CompositeType.PureClass) { // 用 shallowEqual 对比 props 和 state 的改动 // 如果都没改变就不用更新 shouldUpdate = !shallowEqual(prevProps,nextProps) || !shallowEqual(inst.state,nextState); } } 简而言之, 关于 shallowEqual,shallowCompare,PureRenderMixin 的联系我们知道在
var shallowEqual = require('shallowEqual'); function shallowCompare(instance,nextProps,nextState) { return ( !shallowEqual(instance.props,nextProps) || !shallowEqual(instance.state,nextState) ); } module.exports = shallowCompare;
var shallowCompare = require('shallowCompare'); var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function(nextProps,nextState) { return shallowCompare(this,nextState); },}; module.exports = ReactComponentWithPureRenderMixin; 可以看到, 最后 小结React 之前一直没有针对 ES2015 class 的纯组件写法,虽然自己实现起来并不麻烦,但这也算给出了一个官方的解决方案,可以不再依赖 addon 了。不过 参考资料PureComponent PR (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |