React 中的 constructor(),super(),super(props)的理解

在使用 ES6 的 class 定义 React 组件的时候,经常会看到这样的代码:

constructor(props) {
	super(props);
	// some code
}

看到上面代码,产生两个疑问:

  1. 必须要调用 super() 吗?
  2. super()super(props) 有什么不同?

class

class 是 ES6 提供的 ES5 对象的语法糖,而 React 类组件依赖于 class;

class Person() {
	constructor(name, age) {
		this.name = name;
		this.age = age;
	}
}

let person = new Person("赵云", 22);
console.log(person.name === "赵云");		// true
console.log(person.age === 22);				// true

Person 中的 constructor 相当于对对象的初始化;

constructor

在 React 中,不是每个组件都需要 constructor;

class App extends React.Component {
  render() {
    return (
      <h1>{this.props.title}</h1>
    );
  }
}

App 组件没有 constructor,依然可以运行;
很多时候, 我们需要在 constructor 中访问 this:

constructor() {
  console.log(this); // Syntax error: 'this' is not allowed before super()
}

这是因为当没有调用 super() 时,this 还没有被初始化,所以不能使用;那如果我不使用 this 呢?

constructor() {
	// Syntax error: missing super() call in constructor
}

ES6 会在语法层面强制你调用 super(),所以得出结论:只要存在 constructor 就必须调用 super();

super()

从上面的 App 组件中可以看出,即使没有 constructor,依然可以在 render 中使用 this.props?
这是因为 react 在初始化 class 后,会将 props 自动设置到 this 中,所以在任何地方都可以直接访问 this.props;
除了一个地方:constructor

constructor(props) {
  super();
  console.log(this.props); // undefined
}

所以得出结论:当你需要在 constructor 中访问 this.props 时,才需要设置 super(props);

总结

以下结论适用于 React 的 class 组件:

  1. 只要存在 constructor 就必须调用 super();
  2. 当你需要在 constructor 中访问 this.props 时,才需要设置 super(props);
posted @ 2022-04-26 15:14  太轻描淡写了  阅读(257)  评论(0编辑  收藏  举报