React:生命周期
React 生命周期分为三个阶段:挂载(Mounting)、更新(Updating)和卸载(Unmounting)
挂载阶段(Mounting)
一般会在这个阶段做一些数据获取、事件监听、向服务端发送请求、事件绑定等操作
constructor()
初始化状态(state)和绑定方法。通常在构造函数中完成初始数据的设置。
static getDerivedStateFromProps(props, state)
静态方法
时机:在 render
前调用,用于根据props
更新state
。必须返回一个对象或null。
render()
返回JSX结构,负责组件的渲染逻辑。必须为纯函数,不直接修改状态或与浏览器交互。
componentDidMount()
组件挂载完成后触发。适合执行DOM操作、网络请求或订阅事件等副作用。
更新阶段(Updating)
static getDerivedStateFromProps(props, state)
与挂载阶段相同,在每次更新前调用。
shouldComponentUpdate(nextProps, nextState)
通过返回true
或false
决定是否重新渲染。用于性能优化。
render()
重新渲染组件。
getSnapshotBeforeUpdate(prevProps, prevState)
时机:在 render
之后执行
目的:获取组件更新前的信息
在DOM更新前捕获信息(如滚动位置)。返回值传给componentDidUpdate
。
componentDidUpdate(prevProps, prevState, snapshot)
时机:组件更新完成后执行,可操作DOM或发起网络请求。
卸载阶段(Unmounting)
componentWillUnmount()
时机:组件卸载前调用,用于清理定时器、取消网络请求或移除事件监听。
废弃的生命周期方法
部分方法(如componentWillMount
、componentWillReceiveProps
)已被标记为废弃,推荐使用替代方案(如getDerivedStateFromProps
)。
函数组件的替代方案
通过useEffect
Hook模拟生命周期行为:
useEffect(() => {}, [])
替代componentDidMount
(依赖项为空数组)。useEffect(() => { return () => {} })
替代componentWillUnmount
(返回清理函数)。useEffect(() => {}, [deps])
替代componentDidUpdate
(依赖项变化时触发)。