react 生命周期函数有哪些?

eact 的生命周期函数(Lifecycle Methods)是类组件(Class Component)中用于在不同阶段执行特定逻辑的钩子函数。
它们让我们可以在组件创建、更新、销毁等阶段执行代码,例如发请求、订阅事件、清理资源等。

一、生命周期的三个阶段

React 组件的生命周期大体分为 三个阶段:

阶段 说明
挂载(Mounting) 组件第一次被创建并插入到 DOM 中
更新(Updating) 组件的 props 或 state 改变后重新渲染
卸载(Unmounting) 组件从 DOM 中移除

二、挂载阶段(Mounting)

当组件第一次被渲染时,依次执行以下函数:

生命周期方法 作用 是否常用
constructor(props) 初始化 state、绑定方法
static getDerivedStateFromProps(props, state) 根据 props 派生出 state(少用) ⚠️
render() 渲染 UI(必须)
componentDidMount() 组件挂载后执行(常用于接口请求、DOM 操作、事件监听) ✅✅✅
示例
class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log('constructor');
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  render() {
    console.log('render');
    return <div>Hello React</div>;
  }
}

三、更新阶段(Updating)

当组件的 props 或 state 改变时,触发更新流程:

生命周期方法 作用 是否常用
static getDerivedStateFromProps(props, state) 再次根据 props 派生 state ⚠️
shouldComponentUpdate(nextProps, nextState) 决定是否需要重新渲染(性能优化)
render() 重新渲染 UI
getSnapshotBeforeUpdate(prevProps, prevState) 在更新前获取 DOM 信息 ⚠️
componentDidUpdate(prevProps, prevState, snapshot) 更新完成后执行(可发请求、操作 DOM) ✅✅
示例
class Demo extends React.Component {
  state = { count: 0 };

  shouldComponentUpdate(nextProps, nextState) {
    return nextState.count !== this.state.count;
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('Updated from', prevState.count, 'to', this.state.count);
  }

  render() {
    return <button onClick={() => this.setState({ count: this.state.count + 1 })}>Add</button>;
  }
}

四、卸载阶段(Unmounting)

生命周期方法 作用 是否常用
componentWillUnmount() 组件卸载前执行,用于清理(定时器、事件监听、请求等) ✅✅✅
示例
componentWillUnmount() {
  clearInterval(this.timer);
  window.removeEventListener('resize', this.onResize);
}

五、React 16 后被废弃的生命周期

以下旧生命周期在 React 16 之后 不推荐使用,因为会引起潜在 bug:

废弃方法 替代方案
componentWillMount 使用 constructorcomponentDidMount
componentWillReceiveProps 使用 getDerivedStateFromProps
componentWillUpdate 使用 getSnapshotBeforeUpdate

六、函数组件(Hooks)等价生命周期

React Hooks 出现后,大部分开发用函数组件了。
Hooks 没有“生命周期函数”,但可以通过 useEffect 实现同样的逻辑:

Class 生命周期 Hooks 等价写法
componentDidMount useEffect(() => {...}, [])
componentDidUpdate useEffect(() => {...})(不加依赖或带特定依赖)
componentWillUnmount useEffect(() => { return () => {...} }, [])
示例
import React, { useEffect, useState } from 'react';

function Demo() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('挂载或更新');
    return () => {
      console.log('卸载');
    };
  }, [count]);

  return <button onClick={() => setCount(count + 1)}>Add</button>;
}

总结

阶段 类组件生命周期 函数组件 Hook
挂载 componentDidMount useEffect(() => {...}, [])
更新 componentDidUpdate useEffect(() => {...}, [依赖])
卸载 componentWillUnmount useEffect(() => { return () => {...} }, [])
优化 shouldComponentUpdate React.memo() / useMemo() / useCallback()
posted @ 2025-11-12 09:15  煜火  阅读(18)  评论(0)    收藏  举报