上节课我们把生命周期中更新流程中最难的一套算是讲完了,经过 4 个课时的学习,我们对旧版的生命周期有了了解。这节课我们来对旧版的生命周期做一个阶段性总结
初始化阶段
我们组件要想渲染到页面上就一定要由ReactDOM.render
方法触发进行组件挂载
挂载
挂载阶段的流程很简单,仅仅就只有 4 个生命周期钩子,4 个钩子按照顺序执行。
constructor
方法componentWillMount
方法render
方法componentDidMount
方法(常用,一般在该钩子中做一些初始化的事)
其中构造器方法可以省略掉。
更新阶段
更新阶段自然也是有触发条件的,通常来说都有setState
方法或者父组件重新调用render
方法来触发更新阶段的流程,当然还有用于不修改state
来强制更新的forceUpdate
方法
更新钩子
更阶段的钩子就稍微复杂一点,更新这三个触发条件拥有三个不同的流程。
当使用setState
方法时将按顺序执行
shouldComponentUpdate
方法已判断是否允许更新componentWillUpdate
方法render
方法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/