react生命周期(未完)

react

Posted by EWL on July 10, 2018

基本概念

一个组件的生命周期分为3段: 生成、存在、销毁

生成

当组件在客户端被实例化,第一次被创建时,以下方法依次被调用:

  1. getDefaultProps(用于返回默认的props)
  2. getInitialState(用于获取初始化的state)
  3. componentWillMount(render之前调用,而且也是在组件挂载之前最后一次可以设置state的机会)
  4. render(渲染)
  5. componentDidMount(挂载结束,此时已经有了真实的DOM结构,不需要虚拟DOM了)

当组件在服务端被实例化,首次被创建时,以下方法依次被调用:

  1. getDefaultProps
  2. getInitialState
  3. componentWillMount
  4. render

componentDidMount 不会在服务端被渲染的过程中调用。

存在

存在期就会发生各种交互,类似于点击、客户输入数据等,此时会改变组件的状态。

以下这些方法就会在组件状态改变时调用

  1. componentWillReceiveProps(父组件改变子组件的props时可以使用这个方法,这个方法中可以使用setState来改变state以触发render)
  2. shouldComponentUpdate(但是如果这个时候觉得组件是不需要更新的,那么可以在这个函数中返回false来拒绝render)
  3. componentWillUpdate(这个方法和 componentWillMount 类似,在组件接收到了新的 props 或者 state 即将进行重新渲染前,componentWillUpdate(object nextProps, object nextState) 会被调用)
  4. render
  5. componentDidUpdate(组件更新完毕,类似与componentDidMount,此时具有真实的DOM,可以执行一系列对于DOM的操作)

销毁

  1. componentWillUnmout(每当React使用完一个组件,这个组件必须从 DOM 中卸载后被销毁,此时 componentWillUnmout 会被执行,完成所有的清理和销毁工作,在 componentDidMount 中添加的任务都需要再该方法中撤销,如创建的定时器或事件监听器。)