一、React17.0之前
- componentWillMount()
- 执行场景:render()之前
- 说明:
(1)componentWillMount在render之前执行,所以在该方法中setState不会发生重新渲染;
(2)该方法是服务端渲染中执行的唯一方法;
(3)一般用constructor()代替。
- render()
- 执行场景:
(1)componentWillMountz()之后;
(2)componentWillReceive(nextProps, nextState)之后。
- componentDidMount()
- 执行场景:render()方法之后
- 说明:
(1)在render之后立即执行;
(2)在该方法之中对DOM进行操作,执行之后ref变成实际的DOM;
(3)在该方法之中请求数据,若使用了redux之类的数据服务,在此处可以发出action;
(4)此处setState()可以触发重新渲染。
- componentWillReceiveProps(nextProps)
- 执行场景:
(1)在已经挂载的组件(mounted component)接收到新的props时触发;
(2)该方法在初始化render时不会被调用。 - 说明:
(1)大部分情况下,该生命周期是没有用的,可以略去不写;
(2)若是在constructor函数中初始化了某个state,必须用componentWillReceiveProps来更新state;
(3)调用componenWillReceiveProps的时候,不要去向上分发,调用父组件的相关setState方法,否则会造成死循环。
- shouldComponentUpdate(nextProps, nextState)
- 执行场景:在接收到到新的props或者state时,或者说在componentWillReceiveProp