首页 > 解决方案 > 扩展组件时如何初始化状态?

问题描述

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

但是,我现在想创建一个名为的新类BaseForm,它从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构造函数的状态。如何在不覆盖我要扩展的类的状态的情况下设置状态?

标签: reactjsinheritanceconstructorsetstate

解决方案


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

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

道具和组合为您提供了以明确和安全的方式自定义组件外观和行为所需的所有灵活性。请记住,组件可以接受任意道具,包括原始值、React 元素或函数。

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

错误组件

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

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

然后BaseFormErrorComponent.

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>

    )
  }
}

你可以阅读更多关于React 中的组合与继承的信息


推荐阅读