React组件的生命周期
React 组件的生命周期指的是组件从创建、更新到销毁的整个过程。React 提供了生命周期方法,允许开发者在组件的不同阶段执行特定的操作。React 的生命周期可以分为三个阶段:挂载(Mounting)、更新(Updating) 和 卸载(Unmounting)。
以下是 React 类组件的生命周期方法:
1. 挂载阶段(Mounting)
组件被创建并插入到 DOM 中的过程。
-
constructor(props)
构造函数,用于初始化状态和绑定方法。
注意:如果不初始化状态或不绑定方法,则不需要实现构造函数。 -
static getDerivedStateFromProps(props, state)
在组件挂载或更新时调用,用于根据 props 更新 state。
注意:这是一个静态方法,不能访问this
。 -
render()
必须实现的方法,用于渲染组件的 UI。
注意:render()
是一个纯函数,不能直接修改状态或与 DOM 交互。 -
componentDidMount()
组件挂载完成后调用,通常用于发起网络请求、订阅事件或操作 DOM。
2. 更新阶段(Updating)
当组件的 props 或 state 发生变化时,组件会重新渲染。
-
static getDerivedStateFromProps(props, state)
在组件更新时调用,用于根据新的 props 更新 state。 -
shouldComponentUpdate(nextProps, nextState)
决定组件是否需要重新渲染。返回true
则更新,返回false
则跳过更新。
注意:可以用于性能优化。 -
render()
重新渲染组件。 -
getSnapshotBeforeUpdate(prevProps, prevState)
在 DOM 更新之前调用,用于获取更新前的 DOM 信息(如滚动位置)。
注意:返回值会作为参数传递给componentDidUpdate
。 -
componentDidUpdate(prevProps, prevState, snapshot)
组件更新完成后调用,通常用于操作 DOM 或发起网络请求。
3. 卸载阶段(Unmounting)
组件从 DOM 中移除的过程。
componentWillUnmount()
组件卸载前调用,通常用于清理定时器、取消网络请求或移除事件监听器。
4. 错误处理(Error Handling)
当组件渲染过程中发生错误时调用。
-
static getDerivedStateFromError(error)
当子组件抛出错误时调用,用于更新 state 以显示错误 UI。 -
componentDidCatch(error, info)
当子组件抛出错误时调用,用于记录错误信息。
生命周期图示
以下是 React 生命周期的简化图示:
挂载阶段:
constructor → getDerivedStateFromProps → render → componentDidMount
更新阶段:
getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate
卸载阶段:
componentWillUnmount
错误处理:
getDerivedStateFromError → componentDidCatch
函数组件的生命周期替代方案
在函数组件中,React 提供了 useEffect
Hook 来模拟生命周期方法:
-
挂载和更新:
useEffect(() => { ... }, [])
第二个参数为空数组时,相当于componentDidMount
;有依赖项时,相当于componentDidUpdate
。 -
卸载:
useEffect(() => { return () => { ... } }, [])
返回的函数相当于componentWillUnmount
。 -
错误处理:目前函数组件没有直接替代
getDerivedStateFromError
和componentDidCatch
的方法,需要使用类组件或错误边界组件。
总结
- 类组件的生命周期方法提供了对组件生命周期的细粒度控制。
- 函数组件通过
useEffect
实现了类似的功能,代码更简洁。 - 在实际开发中,推荐使用函数组件和 Hooks,因为它们更符合 React 的未来发展方向。