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

来源

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值