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 组件和函数式组件中生命周期的关系和区别:

// 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,具体行为通过参数控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值