一张图解释
 
React 类组件生命周期方法
React 类组件的生命周期可以分为三个主要阶段:
挂载(Mounting)
更新(Updating)
卸载(Unmounting)
- 挂载阶段
 在组件实例被创建并插入到 DOM 中时调用。
- constructor(): 构造函数,初始化 state 和绑定方法。
- static getDerivedStateFromProps(props, state): 在调用 render 方法之前调用,并且在- 初始挂载及后续更新时都会被调用。它应该返回一个对象来更新 state,如果返回 null 则不更新任何内容。
- render(): 必须的方法,返回要渲染的内容。
- componentDidMount(): 在组件挂载后(插入 DOM 树中)立即调用。这里适合发送网络请求或订阅。
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log('Constructor');
  }
  static getDerivedStateFromProps(props, state) {
    console.log('getDerivedStateFromProps');
    return null;
  }
  componentDidMount() {
    console.log('componentDidMount');
  }
  render() {
    console.log('Render');
    return <div>{this.state.count}</div>;
  }
}
- 更新阶段
 当组件的 props 或 state 发生变化时会触发更新。
- static getDerivedStateFromProps(props, state): 同上。
- shouldComponentUpdate(nextProps, nextState): 决定组件是否重新渲染,返回 true(默认)或 false。
- render(): 同上。
- getSnapshotBeforeUpdate(prevProps, prevState): 在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。
- componentDidUpdate(prevProps, prevState, snapshot): 在组件更新后被调用。这里可以做一些基于 DOM 操作的工作,更新后的 state 和 props 可以通过参数访问。
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  static getDerivedStateFromProps(props, state) {
    console.log('getDerivedStateFromProps');
    return null;
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate');
    return true;
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log('getSnapshotBeforeUpdate');
    return null;
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('componentDidUpdate');
  }
  render() {
    console.log('Render');
    return <div>{this.state.count}</div>;
  }
}
- 卸载阶段
 在组件从 DOM 中移除时调用。
- componentWillUnmount(): 在组件卸载及销毁之前直接调用。在这里可以执行必要的清理操作,例如清除定时器、取消网络请求或清理在 componentDidMount 中创建的订阅。
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  componentWillUnmount() {
    console.log('componentWillUnmount');
  }
  render() {
    return <div>{this.state.count}</div>;
  }
}
React Hooks 生命周期
在函数组件中使用 React Hooks(如 useEffect)来模拟类组件的生命周期方法。
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
  const [count, setCount] = useState(0);
  // componentDidMount 和 componentDidUpdate
  useEffect(() => {
    console.log('Component did mount or update');
    return () => {
      // componentWillUnmount
      console.log('Component will unmount');
    };
  }, [count]); // 依赖数组,count 变化时触发 useEffect
  return <div>{count}</div>;
};
总结
- 类组件有明确的生命周期方法,用于在组件的不同阶段执行特定操作。
- 函数组件使用 Hooks (useEffect) 来处理副作用,模拟类组件的生命周期方法。
- useEffect 可以根据依赖数组来决定副作用的执行时机(挂载、更新、卸载)。
- 但组件生命周期
- 父子组件生命周期,和Vue的一样



















