前端/移动开发面试题更新 2026-08-05

请解释 React 组件的生命周期是什么,并说明各生命周期函数的执行顺序(包括挂载、更新、卸载阶段)。

前端/移动开发技术原理React

考察说明

考查对 React 组件生命周期概念的理解以及各阶段钩子函数的执行顺序。

回答思路

  1. 【回答框架 1】生命周期指组件从创建、挂载、更新到卸载的整个过程,React 在不同阶段提供钩子函数供开发者执行逻辑。传统类组件生命周期分为三个阶段:挂载、更新、卸载。
  2. 【回答框架 2】挂载阶段依次执行 constructor、getDerivedStateFromProps、render、componentDidMount;更新阶段依次执行 getDerivedStateFromProps、shouldComponentUpdate、render、getSnapshotBeforeUpdate、componentDidUpdate;卸载阶段执行 componentWillUnmount。
  3. 【回答框架 3】React 16.3 起部分旧生命周期(如 componentWillMount)被标记为不安全,新版本推荐使用 getDerivedStateFromProps 和 getSnapshotBeforeUpdate,同时函数组件通过 useEffect 模拟生命周期行为。
  4. 【关键点 1】挂载顺序:constructor → getDerivedStateFromProps → render → componentDidMount
  5. 【关键点 2】更新顺序:getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate
  6. 【关键点 3】卸载时执行 componentWillUnmount,用于清理定时器、取消订阅等
  7. 【易错点 1】容易混淆 getDerivedStateFromProps 与 componentWillReceiveProps 的用法,前者是静态方法,不能访问 this。
  8. 【易错点 2】忽略 shouldComponentUpdate 的返回值对渲染的影响,导致不必要的渲染或漏更新。
  9. 【易错点 3】在 componentDidUpdate 中直接调用 setState 而不加条件,可能造成无限循环。