澄清基于 React Class 的组件构造函数

Clarification on React Class based component constructor

我正在复习一些 React Js 基础知识,我需要一些关于在基于 React class 的组件中使用构造方法的说明。我通常的做法是声明一个基于 class 的组件并在不使用构造函数的情况下定义状态,如下所示:

import React, { Component } from 'react';

export class Testing extends Component {
  state = {
    example: "Hello World!!!"
  }

  render() {
    return <div>
      {this.state.example}
    </div>;
  }
}

export default Testing;

由于状态在没有(看似)无意义的构造函数的情况下非常容易使用,所以我开始问自己构造函数的用途。只是为了澄清我所说的构造函数的意思,当你声明这样的状态而不是上面的例子时:

constructor(props) {
  super(props)

  this.state = {
    example: "Hello World!!!"
  }
}

我在 react 文档中找到了使用构造函数是最佳实践的建议,但没有说明原因。经过一番搜索后,我找到了一个来源,建议构造函数为您提供访问 props 的权限。我对此进行了测试,并确实看到了构造函数如何提供对道具的访问权限;然而,class 可以在不使用构造函数的情况下访问 props,只需声明 this.props.myTest。我也通过在父组件中定义道具并将它们向下钻取到子组件来测试这一点。我可以使用 this.props.myTest 语句很好地访问道具,不需要构造函数。所以我的问题是,“构造函数具体做什么,什么时候有必要(或有必要)?”

"什么时候需要构造函数?":

构造函数不是必需的,如果你不需要的话。

您可能需要一个构造函数,例如如果您需要将方法绑定到 class 实例(以便 this 一直指向 class 实例,如果您将函数传递给其他执行上下文):

export class Testing extends Component {
  constructor( props ) {
    super( props );
    this.myMethod = this.myMethod.bind( this );
  }
  
  myMethod(){
    console.log( this.props ); 
  }

  render() {
    return <button onClick={ this.myMethod }>
      click
    </button>;
  }
}

“构造函数具体做什么”?

构造函数在 javascript 中“创建实例”。所以没有构造函数,就不会有实例。 但本质上总是有一个构造函数,即使您没有专门定义一个构造函数。

您可以定义一个构造函数来覆盖默认构造函数或添加一些额外的逻辑 运行 除了 super-constructor.

在 React

中访问 this.props

javascript 中,您无法在不调用 super(props).

的情况下访问 this.props

注意构造函数参数props和实例属性this.props是不同的“东西”。 现在让我们重命名构造函数参数,使其更明显:

class SuperClass {
  constructor( constructorArguments ) {
    this.props = constructorArguments;
  }
}

class DerivedClass extends SuperClass {
  constructor( props ) {
    super();                   // <-- call the SuperClass constructor
  }
  method(){
    console.log( this.props ); // <-- this.props is obviously never defined
  }
}

const instance = new DerivedClass('some props');
instance.method();

但是 React 无论如何“采取措施”分配 this.props, 即使从未调用 super(props)

但那是稍后发生的(在构造函数完成后), 所以你可以稍后在其他方法中访问 this.props,但不能在构造函数中访问:

export class Testing extends Component {

  constructor( constructorArguments ) {
    super();                   // <-- super() is called without arguments
    console.log( this.props ); // <-- this.props is undefined
  }

  render() {
    console.log( this.props ); // <-- React sorted it out, now this.props is available 
    return null;
  }
}

如果将构造函数参数传递给超级 class 构造函数,则可以访问 this.props 在构造函数中:

constructor( constructorArguments ) {
  super( constructorArguments );   // <-- super() is called with arguments
  console.log( this.props );       // <-- this.props is available
}

React recommends to call super(props) 无论如何,避免在以后的更改中引入错误。 我可能会补充说,它是非常少的额外代码,不会造成任何伤害。

定义状态

class fields 并不总是可用的,因此您必须在其中定义状态 构造函数,as the React example shows(如 this.state = { value: 'value' })。

我个人认为现在使用 class 字段可能没问题,但我总是 倾向于遵循官方文档,即使它可能已过时。还有 可能是我不知道的含义。

另请参阅: