ReactJS:在组件 class 中不需要构造函数的一些标准是什么?

ReactJS: What are some criteria for not needing a constructor in a component class?

我想知道组件的 class 声明中不需要构造函数的条件。我认为这是针对无状态组件的,但是还有其他原因吗?例如,组件内部没有任何功能(除了生命周期功能)会不会是一个?

我通常只在组件有内部状态时才添加构造函数,我需要在使用它之前设置它,否则我会省略构造函数。组件中有函数不影响我这方面的决定

我认为在此处留下 react docs 的摘录(强调我的)是合适的:

The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.

如果你使用 babel stage-2 预设,在任何情况下你实际上根本不需要构造函数,因为它提供了 class 有效替换其用法的属性:

class Component extends React.Component {
  constructor() {
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() { console.log('click'); }
}

变成

class Component extends React.Component {
  state = {};
  handleClick = () => console.log('click');
}

忽略这一点,只有当你需要将组件方法绑定到它的上下文时,或者如果你需要初始化 state 属性.

时,才需要构造函数

另一种情况是,如果您需要对 this.props class 属性 做一些事情,但这被 React 认为是反模式。

class Component extends React.Component {
  constructor() {
    this.state = {
      // don't do this! anti-pattern! duplication of source of truth!
      duplicatedState: this.props.myName,
    };
  }
}