首页 > 解决方案 > React:PureComponent 和组件原型

问题描述

零件:

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

纯组件:

function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;

function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

我真的很困惑ComponentDummy。为什么我们不能使用pureComponent.prototype = {} 有人能解释一下下面的代码实际上做了什么吗???

const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;

如果你能分享我的原型链,我真的很Component Dummy感激PureComponent

标签: javascriptreactjs

解决方案


因为如果我们使用PureComponent.prototype = new Component(),函数 Component 会被调用,并且 props、context 和 refs 也会被创建,这会导致占用更多的存储空间。

但是如果我们使用PureComponent.prototype = new ComponentDummy(),我们可以节省那些无用的存储空间。

我想。


推荐阅读