2022年前端React的100道面试题的第7题:组件的constructor

问题

React17生命周期构造函数constructor理解正确的是?

 

选项

A 仅在需要初始化 state ,或者方法绑定时声明 constructor。

B 在 React 组件挂载之前,会调用它的构造函数。

C 在 constructor() 函数中可以调用 setState() 方法,也可以直接给 this.state 赋值;

D 要避免在构造函数中引入任何副作用或订阅。如遇到此场景,请将对应的操作放置在 componentDidMount 中。

 

答案

A、B、D

 

解答

如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。通常,在 React 中,构造函数仅用于以下两种情况:

  • 通过给 this.state 赋值对象来初始化内部 state。

  • 为事件处理函数绑定实例。

 

constructor不是必填

React 中通过继承的方式定义 class 组件时,可以缺省 constructor 构造函数,由 ES6 的继承规则得知,不管子类写不写 constructor,在 new 实例的过程都会给补上 constructor

 

super是必须调用的

可以不写constructor,一旦写了constructor,就必须在此函数中写super(),否则会报错:

class Example extends React.Component {
 constructor() {}
 render() {
   return <h1>Hello, {this.props.name}</h1>;
}
}

Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

 

此时组件才有自己的this,在组件的全局中都可以使用this关键字,否则如果只是constructor 而不执行 super() 那么以后的this都是错的。

 

不要在组件构造函数中调用 setState() 方法

如果需要修改 state,直接在构造函数中为this.state 赋值初始即可。

class Example extends React.Component {
 constructor(props) {
   super(props)
   this.setState({ name: "React" })
}
 render() {
   return <h1>Hello, {this.props.name}</h1>;
}
}

会报如下警告:

Warning: Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the %s component.%s" "setState" "Welcome"

 

避免派生状态

避免将 props 的值复制给 state,你可以直接使用 this.props.color。除非你是想编写 ”非受控组件“,那么此 color 属性仅做默认值使用,因此建议在 props.color 命名上优化为 ”initialColor“ 或 ”defaultColor“。

constructor(props) {
   super(props);
   this.state = { color: props.initialColor };
}

 

资源

组件的生命周期

关于react组件中的constructor和super

 

来源

搜索《考试竞技》微信小程序

posted @ 2021-11-29 08:12  nachao  阅读(130)  评论(0编辑  收藏  举报