参考:有关React的生命周期
1.constructor可以省略,但是区别:
有constructor的子类:类里面会多一个constructor方法。有constructor的this实例:可以定义自己的state的初始状态,如果不需要,建议使用无状态组件即函数组件。
2.super中的props作用:
2.1 有constructor,必须有super()
如果写constructor的话,一定要在函数中协商super(),这样的话组件才有自己的this,在组建全局中可以使用this关键字。
官方文档中说:子类自己的this对象,必须通过父类的构造函数完成,得到与父类同样的实例属性和方法,再对其加工,加上子类自己的,如果不调用super方法的haunted,就得不到this对象。
2.2 super里面必须写props吗?
- 有props时:可以在constructor生命周期中使用this.props,常用与this.state中用props初始化状态。
- 无props:不可以在constructor中使用this.props,但在其他生命周期中可以使用。
3.生命周期
3.1 生命周期执行次数:
- 只执行一次: constructor、componentWillMount、componentDidMount
- 执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate
- 有条件的执行:componentWillUnmount(页面离开,组件销毁时)
- 不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props
3.2组件生命周期执行顺序
-
第一次渲染的顺序(不涉及setState更新)
触发App的生命周期
这时候触发App的setState的生命周期
触发parent的生命周期函数
触发child自身组件的生命周期
可以认为,初次渲染时候执行:constructor,componentWillMount,render。完成时执行componentDidMount。更新时:从上而下执行componentWillReceiveProps ,componentWillUpdate,render。从下而上执行componentDidUpdate。
总体执行顺序
如果有多套组件,则一套执行完再执行下一套