转载地址:https://blog.csdn.net/u012149906/article/details/102821641
constructor是否有必要写?
答:ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上。
ES6的继承机制不同,实质是先创造父类的实例对象this,所以必须先调用super方法,
然后再用自己的构造函数修改this。
如果子类没有定义constructor方法,这个方法会被默认添加,
也就是说,不管有没有显示定义,任何一个子类都有constructor方法。
如果组件要定义自己的state初始状态的话,需要写在constructor方法中,
如果没有state,就可以不用constructor函数。
constructor方法中super,传递的参数props是否有必要写?
答:在类中写了constructor方法,就必须使用super(),
这样组件才有自己的this,在组件的全局中都可以使用this关键字,
否则如果只是constructor而不执行super()那么之后的this都是错的。
super中的参数必须写参数props吗?
答:在constructor中使用this.props的时候,super需要加入props。
如果constructor中不通过super来接收props,在其他生命周期,
诸如componentWillMount、componentDidMount、render中能直接使用this.props吗?
答:可以的,react在除了constructor之外的生命周期已经传入了this.props了,完全不受super(props)的影响。