React 组件生命周期对比:Class vs. 函数式

在 React 中,Class 组件和函数式组件的生命周期存在一些差异。通过对 React 中 Class 组件和函数式组件的生命周期进行对比,详细探讨了它们在设计哲学、生命周期管理和开发技巧上的异同。全面了解 React 中两种组件类型的生命周期特点,以及如何灵活运用它们来构建现代化的 React 应用。

React Class 组件生命周期:

  1. constructor: 组件实例化时调用,用于初始化状态和绑定方法。

  2. componentDidMount: 组件挂载后调用,可以进行 DOM 操作或发起数据请求。

  3. componentDidUpdate: 组件更新后调用,用于处理更新前后的状态差异。

  4. componentWillUnmount: 组件即将被卸载时调用,用于清理定时器或取消订阅等操作。

React 函数式组件生命周期:

  1. useState 和 useEffect: 使用 useState 定义状态,使用 useEffect 进行副作用操作,相当于 Class 组件的 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。

下面是一个简单的示例,演示了 Class 组件和函数式组件中生命周期的关系和区别:

js 复制代码
// Class 组件
class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    console.log("Component mounted");
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("Component updated");
  }

  componentWillUnmount() {
    console.log("Component will unmount");
  }

  render() {
    return (
      <div>
        <h2>Class Component</h2>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

// 函数式组件
import React, { useState, useEffect } from "react";

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

  // 模拟 componentDidMount
  useEffect(() => {
    console.log("Component mounted");
    // 清理函数,模拟 componentWillUnmount
    return () => {
      console.log("Component will unmount");
    };
  }, []);

  // 模拟 componentDidUpdate
  useEffect(() => {
    console.log("Component updated");
  }, [count]); // 仅在 count 发生变化时执行

  return (
    <div>
      <h2>Functional Component</h2>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default FunctionalComponent;


// 父组件
function App() {
  const [showClassComponent, setShowClassComponent] = React.useState(true);

  return (
    <div>
      {showClassComponent ? <ClassComponent /> : <FunctionalComponent />}
      <button onClick={() => setShowClassComponent(!showClassComponent)}>
        Toggle Component
      </button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

在上面的示例中,Class 组件和函数式组件都实现了一个计数器,当点击按钮时,计数器会递增。在浏览器控制台中可以看到不同生命周期函数的输出。

总结一下:

  • Class 组件中的生命周期函数需要手动实现,而函数式组件使用 useEffect 来模拟生命周期行为。
  • 函数式组件中的 useEffect 可以模拟 componentDidMount、componentDidUpdate 和 componentWillUnmount,具体行为通过参数控制。
相关推荐
wen's8 小时前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
Jackson_Mseven15 小时前
面试官:useEffect 为什么总背刺?我:闭包、ref 和依赖数组的三角恋
前端·react.js·面试
前端小盆友17 小时前
从零实现一个GPT 【React + Express】--- 【2】实现对话流和停止生成
前端·gpt·react.js
OLong18 小时前
2025年最强React插件,支持大量快捷操作
前端·react.js·visual studio code
摸鱼仙人~18 小时前
重塑智能体决策路径:深入理解 ReAct 框架
前端·react.js·前端框架
namehu18 小时前
浏览器中的扫码枪:从需求到踩坑再到优雅解决
前端·react.js
杨进军18 小时前
React 使用 MessageChannel 实现异步更新
react.js
namehu18 小时前
浏览器中的打印魔法:Lodop与系统打印机
前端·react.js
如果'\'真能转义说19 小时前
React自学 基础一
前端·react.js·前端框架
巴巴_羊19 小时前
react setstate
react.js