扩展组件时如何初始化状态?

How do I initialize state when I'm extending a component?

我有一个名为 ErrorComponent 的组件,其状态在其构造函数中初始化。

但是,我现在想创建一个名为 BaseForm 的新 class,它从 ErrorComponent 扩展而来。

但如果我这样做

export default class BaseForm extends ErrorComponent {
    constructor(props) {
            super(props);
            this.setState({
                reason: null
            });

它对我大吼大叫,说我不应该在构造函数中使用 setState

如果我这样做

export default class BaseForm extends ErrorComponent {
    constructor(props) {
            super(props);
            this.state = {
                reason: null
            };

它似乎正在覆盖 ErrorComponent 构造函数的状态。如何在不覆盖我正在扩展的 class 的状态的情况下设置状态?

export default class BaseForm extends ErrorComponent {
    constructor(props) {
            super(props);
            this.state = Object.assign(this.state, {
                reason: null,
            });

您不应该在 React 中使用继承,直到或除非无法通过组合实现所需的功能。这是 React 反模式。

React 具有强大的组合模型,建议使用组合而不是继承来重用组件之间的代码。

Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.

你应该像下面这样使用它。

错误组件

export default class ErrorComponent extends Component {
  constructor(props) {
    super(props);
    this.setState({...this.props.childState });
  }

  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}

然后用ErrorComponent包裹BaseForm

export default class BaseForm extends Component {
  constructor(props) {
    super(props);
    this.setState({
      reason: null
    });
  }

  render() {
    return (
      <ErrorComponent childState={this.state}>
        <div>
          some thing
      </div>
      </ErrorComponent>

    )
  }
}

您可以阅读有关 Composition vs Inheritance in React

的更多信息