React 作为前端领域的重要框架之一,其生命周期方法在组件的创建、更新和销毁过程中扮演着关键的角色。在本文中,我们将深入探讨 React 16 版本的生命周期,理解每个阶段的作用及调用时机。
-
挂载阶段:
constructor
: 初始化。render
: 渲染 UI。componentDidMount
: 添加到 DOM 后执行。
-
更新阶段:
shouldComponentUpdate
: 控制重新渲染。render
: 渲染。componentDidUpdate
: 更新后执行。
-
卸载阶段:
componentWillUnmount
: 销毁前执行。
-
错误处理:
static getDerivedStateFromError
: 渲染阶段错误处理。componentDidCatch
: 后代组件错误处理。