上节课我们把生命周期中更新流程中最难的一套算是讲完了,经过 4 个课时的学习,我们对旧版的生命周期有了了解。这节课我们来对旧版的生命周期做一个阶段性总结

初始化阶段

我们组件要想渲染到页面上就一定要由ReactDOM.render方法触发进行组件挂载

挂载

挂载阶段的流程很简单,仅仅就只有 4 个生命周期钩子,4 个钩子按照顺序执行。

  1. constructor方法
  2. componentWillMount方法
  3. render方法
  4. componentDidMount方法(常用,一般在该钩子中做一些初始化的事)

其中构造器方法可以省略掉。

更新阶段

更新阶段自然也是有触发条件的,通常来说都有setState方法或者父组件重新调用render方法来触发更新阶段的流程,当然还有用于不修改state来强制更新的forceUpdate方法

更新钩子

更阶段的钩子就稍微复杂一点,更新这三个触发条件拥有三个不同的流程。

当使用setState方法时将按顺序执行

  1. shouldComponentUpdate方法已判断是否允许更新
  2. componentWillUpdate方法
  3. render方法
  4. componentDidUpdate方法

如果我们是由父组件重新调用render触发的更新,那么则在shouldComponentUpdate方法之前调用componentWillReceiveProps方法,而且该方法是在子组件接收到props之前调用的。

如果是用过forceUpdate来触发了更新,那么就直接跳过shouldComponentUpdate方法直接进行更新流程。但是这个方法几乎不怎么用。

卸载阶段

卸载阶段其实是最简单的一个流程,由ReactDOM.unmountComponentAtNode触发,当卸载流程触发后将在卸载组件前调用componentWillUnmount方法,当该方法执行完毕之后直接卸载组件。

componentWillUnmount方法也非常常用,一般都在这个钩子做做一些收尾的工作,比如关闭定时器啊等等

最常用且必须使用

render方法,如果我们没有render方法,这个组件是不是就没有意义了。所以说这个是一直伴随我们的一个方法。

总结

三大常用生命周期钩子:

  • render方法
  • componentDidMount方法
  • componentWillUnmount方法

Copyright statement:The articles of this site are all original if there is no special explanation, indicate the source please when you reprint.

Link of this article:https://work.lynchow.com/article/summary_lifecycle_old/