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,具体行为通过参数控制。
相关推荐
用户298698530146 小时前
React 前端实现 Word 与 OpenXML 双向转换的完整实践
javascript·react.js
月夏1 天前
我把全栈项目塞进已有 nginx 的服务器,卡我最久的是三个斜杠
nginx·react.js·docker
清晨Coding4 天前
为什么用 React Developer Tools 查看组件树这么乱?
前端·react.js
生活的囚徒5 天前
从一堆Excel到一套系统:项目管理+研发管理双门户的落地实践
react.js
ZhengEnCi6 天前
React 19 加 Vite 6 企业级前端项目目录结构:无路由 SPA、zustand 与 Tailwind 4 的分层架构指南
react.js
用户298698530146 天前
React 前端实现 Excel 与 CSV 互转:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
Highcharts.js8 天前
Highcharts Orbit 完全指南:把每一张图表变成交互式分析工具
react.js·前端框架·highcharts·orbit·使用指南·ai 图表·交互式分析工具
鸿蒙开发8 天前
小程序存档写到一半怎么办?双槽保存与损坏恢复实战
前端·javascript·react.js
古茗前端团队10 天前
由 key 引发的思考
前端·javascript·react.js
用户2986985301413 天前
React 前端将 Excel 工作表导出为图片的技术实践
javascript·react.js·excel