react生命周期,详细版本
React 组件的生命周期分为三个阶段:挂载(Mounting)、更新(Updating) 和 卸载(Unmounting)。以下是类组件生命周期的详细说明(基于 React 16.3+ 版本):
一、挂载阶段(Mounting)
组件实例被创建并插入 DOM 时的流程:
- constructor(props)
○ 用途:初始化状态(this.state)或绑定方法。
○ 注意:必须调用 super(props),否则 this.props 会未定义。
○ 避免副作用(如 API 调用),应在 componentDidMount 中进行。 - static getDerivedStateFromProps(nextProps, prevState)
○ 用途:根据新的 props 更新 state。
○ 是静态方法,无法访问 this,必须返回一个对象更新 state 或返回 null 不更新。
○ 替代旧版 componentWillReceiveProps。 - render()
○ 用途:返回 JSX,描述 UI 结构。
○ 必须为纯函数,不能修改组件状态或直接与 DOM 交互。 - componentDidMount()
○ 用途:组件已挂载到 DOM 后调用。
○ 常见操作:发起网络请求、添加事件监听、操作 DOM 等副作用。
二、更新阶段(Updating)
当组件的 props 或 state 发生变化时触发:
- static getDerivedStateFromProps(nextProps, prevState)
○ 同挂载阶段,在每次渲染前触发(包括初始挂载和更新)。 - shouldComponentUpdate(nextProps, nextState)
○ 用途:决定是否重新渲染组件(默认返回 true)。
○ 返回 false 可跳过本次渲染及后续生命周期方法(如 render, componentDidUpdate)。
○ 性能优化:避免不