react里面的constructor

297 阅读1分钟

在初学react的时候,每次都将构造器constructor写出来,但是又不懂实际的含义。官网上的描述:如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。 这样看来,只有两种情况需要写constructor。

1,初始化 state

class Demo extends React.Component {
  constructor() {
    super()
    this.state = {name: 'dandan'}
  }
  render() {
    return (
      <div>
        测试
      </div>
    );
  }
}

2,进行方法绑定

class Demo extends React.Component {
  constructor() {
    super()
    this.state = {name: 'dandan'}
    this.log = this.log.bind(this)
  }
  render() {
    return (
      <div>
        <button onClick={this.log}>按钮</button>
      </div>
    );
  }
  log() {
    console.log('被点击了')
  }
}

若不存在以上两种情况,constructor构造器可以省略不写

那么在构造器里和super里传与不传props有什么影响呢?

有以下几种情况:

1.都传props

constructor(props) {
    super(props)
    console.log(this.props)  //此处输出props对象
  }

2.都不传props

constructor() {
    super()
    console.log(this.props)  //此处输出undefined
  }
  1. 构造器传但是super不传props
constructor() {
    super()
    console.log(this.props)  //此处输出undefined
  }
  1. 构造器不传但是super传props
constructor() {
    super(props)
    console.log()  //报错
  }

由此看出,构造器里是否接收props参数,是否传递给super,取决于你是否希望在构造器里通过this使用props