React 组件的生命周期
一. 旧版本生命周期
constructor(props)
:构造器 完成了React数据的初始化componentWillMount
:组件将要挂载的钩子componentDidMount
:组件挂载完毕的钩子componentWillReceiveProp(props)
:组件将要接收组件新的props的钩子shouldComponentUpdate
:控制组件是否继续更新
必须返回值 true/false,返回值默认为 true。componentWillUpdate
:组件将要更新的钩子componentDidUpdate
:组件更新完成的钩子render
:页面渲染componentWillUnmount
:销毁组件之前的钩子
各阶段生命周期执行顺序:
- 初始化阶段,挂载时
constructor
=>componentWillMount
=>render
=>componentDidMount
- 更新阶段
componentWillReceiveProps
=>shouldComponentUpdate
=>componentWillUpdate
=>render
=>componentDidUpdate
- 销毁组件
componentWillUnmount
二. 新版本生命周期
constructor(props)
:构造器 完成了React数据的初始化。getDerivedStateFromProps(props, state)
:若 state 的值在任何时候都取决于 props,那么可以使用 getDerivedStateFromProps。
使用时需加static
修饰符,如:static getDerivedStateFromProps(props, state)
。
应返回一个对象来更新 state,如果返回 null 则不更新任何内容。shouldComponentUpdate
:控制组件是否继续更新
必须返回值 true/false,返回值默认为 true。render
:页面渲染。componentDidMount
:组件挂载完毕的钩子。getSnapshotBeforeUpdate
:最近更新渲染(提交到 DOM 节点)之前调用。
应返回 snapshot 的值(或 null)。componentDidUpdate(prevProps, prevState, snapshotValue)
:组件更新完成的钩子。componentWillUnmount
:销毁组件之前的钩子。
各阶段生命周期执行顺序:
- 初始化阶段,挂载时
constructor
=>getDerivedStateFromProps(props, state)
=>render
=>componentDidMount
- 更新阶段
getDerivedStateFromProps(props, state)
=>shouldComponentUpdate
=>render
=>getSnapshotBeforeUpdate
=>componentDidUpdate
- 销毁组件
componentWillUnmount
三. 新旧生命周期对比
- 废弃三个生命周期钩子
componentWillMount
componentWillReceiveProps
componentWillUpdate
- 新增两个生命周期钩子
getDerivedStateFromProps
getSnapshotBeforeUpdate