react主要思想通过构建可复用组件来构建界面,所谓组件就是有限状态机(FSM),有限个状态以及这些状态之间的转移和动作等行为的模型。react正是利用这个概念来实习通过管理状态对组件进行管理。废话不多说,下面看这些生命周期在不同的组件阶段,他们的执行顺序是如何
- 初始化组件
getDefaultProps -> getInitialState -> componenWillMount -> render -> componentDidMount - 第二次渲染
getInitialState -> componenWillMount -> render -> componentDidMount - props changed
ComponentWillRecieveProps -> shouldComponentUpdate ->render->componentDidupdate - state changed
shouldComponentUpdate ->render->componentDidupdate - 卸载
ComponentunMount
自定义组件生命周期主要通过三个阶段来完成,Mounting、recieveProps、unMounting。
- Mounting
这个阶段负责管理生命周期中的getInitialState / componentWillMount / render/ componentDidMount,由于getDefaultProps是在构造方法里面调用,所以getDefaultProps只在初始化组件的时候调用,以后都不在调用,这里要注意不要在componentWillMount调用setState方法,因为此时setState是不会触发re-render,而是会对state进行合并操作,而且此时state也不是最新的,因为 instance.state = this._processPendingState是在componentWillMount之后执行,只有render的时候才是最新 - RecieveProps
这个阶段负责管理生命周期中的 componentWillRecieveProps / componentShouldUpdate/ componentWillUpdate / render / componentDidUpdate, 这里要注意在componentWillRecieveProps / componentShouldUpdate/ componentWillUpdate中都不能调用setState,除了效果跟上述componentWillMount一样之外,在componentShouldUpdate、componentWillUpdate和render中调用setState还会触发死循环,因为这两生命周期中调用setstate,此时this._pendingStateQueue!=null,会触发调用updateComponent,而updateComponent又会调用componentwillUpdate和componentShouldUpdate - unMount
此阶段会执行并重置所有的参数、更新队列和状态,清除公共类,完成组件卸载工作。此阶段调用setState不会re-render
react16最新生命周期
新的生命周期
Mounting(加载阶段:涉及4个钩子函数)
constructor()
加载的时候调用一次,可以初始化state
static getDerivedStateFromProps(props, state)
组件每次被rerender的时候,包括在组件构建之后(虚拟dom之后,实际dom挂载之前),每次获取新的props或state之后;每次接收新的props之后都会返回一个对象作为新的state,返回null则说明不需要更新state;配合componentDidUpdate,可以覆盖componentWillReceiveProps的所有用法
render()
react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行
componentDidMount()
组件渲染之后调用,只调用一次
Updating(更新阶段:涉及5个钩子函数)
static getDerivedStateFromProps(props, state)
组件每次被rerender的时候,包括在组件构建之后(虚拟dom之后,实际dom挂载之前),每次获取新的props或state之后;每次接收新的props之后都会返回一个对象作为新的state,返回null则说明不需要更新state;配合componentDidUpdate,可以覆盖componentWillReceiveProps的所有用法
shouldComponentUpdate(nextProps, nextState)
组件接收到新的props或者state时调用,return true就会更新dom(使用diff算法更新),return false能阻止更新(不调用render)
render()
react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行
getSnapshotBeforeUpdate(prevProps, prevState)
触发时间: update发生的时候,在render之后,在组件dom渲染之前;返回一个值,作为componentDidUpdate的第三个参数;配合componentDidUpdate, 可以覆盖componentWillUpdate的所有用法
componentDidUpdate()
组件加载时不调用,组件更新完成后调用
Unmounting(卸载阶段:涉及1个钩子函数)
组件渲染之后调用,只调用一次
Error Handling(错误处理)
componentDidCatch(error,info)
任何一处的javascript报错会触发