生命周期就像是人的一生,在特定的时候担任特定的角色。
本文介绍的是旧版本react的生命周期
从图中可以看出,生命周期可以分为初始化阶段
、更新阶段
和组件卸载阶段
初始化阶段
- constructor() // 构造器
- componentWillMount() // 组件将要挂载的钩子
- render()
- componentDidMount() // 组件挂载完毕的钩子
16.3版本后
componentWillMount
改名为UNSAFE_componentWillMount
在以后的版本可能后清除
更新阶段
- shouldComponentUpdate() // 控制组件更新的回调函数
- componentWillUpdate() // 组件将要更新的钩子
- render()
- componentDidUpdate() // 组件更新完毕的钩子
16.3版本后
componentWillUpdate
改名为UNSAFE_componentWillUpdate
在以后的版本可能后清除
组件卸载阶段
- componentWillUnmount()
以上是一个组件的生命周期
父子组件中还有一个生命周期钩子
- componentWillReceiveProps()
- 当子组件接收到新的props时就会触发
componentWillReceiveProps
钩子,该钩子会接收新的props,初始化时,不触发该钩子。 -
16.3版本后
componentWillReceiveProps
改名为UNSAFE_componentWillReceiveProps
在以后的版本可能后清除。
注意:调用
forceUpdate()
只会走componentWillUpdate
、render
、componentDidUpdate
这三个钩子。