【问题标题】:How do I initialize state when I'm extending a component?扩展组件时如何初始化状态?
【发布时间】:2020-04-13 03:58:47
【问题描述】:

我有一个名为 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 构造函数的状态。如何在不覆盖我要扩展的类的状态的情况下设置状态?

【问题讨论】:

标签: reactjs inheritance constructor setstate


【解决方案1】:

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

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

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

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

错误组件

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

【讨论】:

    【解决方案2】:
    export default class BaseForm extends ErrorComponent {
        constructor(props) {
                super(props);
                this.state = Object.assign(this.state, {
                    reason: null,
                });
    

    【讨论】:

    • 而且我的依赖项中确实有 "babel-preset-react": "^6.24.1",,因为 this 似乎推荐
    猜你喜欢
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2023-03-08
    • 2019-05-08
    • 2020-02-18
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多