React.js 中 ES5 和 ES6 构造函数的区别

Difference between ES5 and ES6 constructors in React.js

在 React 的源代码中,原型函数有一个带有三个参数的签名:

function Component(props, context, updater) {

但每次我看到有人使用现代 ES6 功能扩展 React.Component,他们声明的构造函数只有 props 如下:

constructor(props)

原型函数和 constructor 文字有什么区别?剩下的两个参数去哪儿了?

所以 Es6 添加了 class 关键字以及它的构造函数。然而,它只是语法糖,仍然像以前一样基于原型模型。 我不知道其他两个 argos,但我猜它与创建自己的词法范围的函数有关。

您显然可以使用组件中提供的所有三个参数。但一般来说,只有在高级情况下我们才使用 props,而不是每次都使用。同样,你可以使用其他的。

这里有一个例子 context api:

ES6 class组件

class ContextConsumer extends React.Component {
  /* 
     contexTypes is a required static property to declare 
     what you want from the context
  */
  static contextTypes = {
      currentUser: React.PropTypes.object
  };
  render() {
    const {currentUser} = this.context;
    return <div>{currentUser.name}</div>;
  }
}

ES6 class 具有覆盖构造函数的组件

class ContextConsumer extends React.Component {
  static contextTypes = {
      currentUser: React.PropTypes.object
  };
  constructor(props, context) {
    super(props, context);
    ...
  }
  render() {
    const {currentUser} = this.context;
    return <div>{currentUser.name}</div>;
  }
}

示例取自 this blog。我会建议您查看博客以更加熟悉它。

另一个参数是 updater,您可能已经使用了它 this.forceUpdate() 并且这样做会调用更新程序。但事实上,我们一般情况下不会直接使用updater。不过,我还没有遇到过在构造函数中使用更新程序的情况。如果您遇到一些高级案例,您也许可以弄清楚。


坦率地说,为了巧妙地使用 react,我什至从未尝试过尽可能地使用 props。它们只是为我们提供的,以便我们可以在需要时在生命周期挂钩中使用。


好吧,让我用react代码稍微解释一下:

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

Component 函数有 3 个参数,在函数内部使用。稍后,它的原型 forceUpdate 被定义,updater 被挂钩以使用 enqueueForceUpdate 将 forceUpdate 入队。因此,this.forceUpdate 实际上调用了 Component 更新程序并允许我们重新渲染组件。我希望现在查看它的原型方法是有意义的。


What is the difference between a prototype function and constructor literal?

据我了解,您想知道为什么使用所需的参数调用构造函数。

使用 class/function 构造函数,以便您可以对函数使用重写。例如,在构造函数中传递 props,你想用它来覆盖。因此,您明确通知函数使用构造函数中使用的道具。