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,具体行为通过参数控制。
相关推荐
邝邝邝邝丹4 小时前
React学习———React Router
前端·学习·react.js
郝开7 小时前
扩展:React 项目执行 yarn eject 后的 package.json 变化详解及参数解析
react.js·前端框架·react
Coding的叶子18 小时前
Node.js 安装 + React Flow 快速入门:环境安装与项目搭建
react.js·node.js·react flow·fgai·react agent
刺客-Andy19 小时前
React 第四十一节Router 中 useActionData 使用方法案例以及注意事项
前端·react.js·前端框架
肠胃炎19 小时前
React事件机制
前端·javascript·react.js
帅帅哥的兜兜20 小时前
next.js实现项目搭建
前端·react.js·next.js
海上彼尚1 天前
秒删node_modules[无废话版]
vue.js·react.js
程序猿阿伟1 天前
《数字分身进化论:React Native与Flutter如何打造沉浸式虚拟形象编辑》
flutter·react native·react.js
果冻kk1 天前
【实战教程】从零实现DeepSeek AI多专家协作系统 - Spring Boot+React打造AI专家团队协作平台
人工智能·spring boot·react.js
进取星辰1 天前
28、动画魔法圣典:Framer Motion 时空奥义全解——React 19 交互动效
前端·react.js·交互