Class 组件与函数组件

React 中 Class 组件和函数组件的区别与使用场景

问题

Class 组件与 Function 组件的区别是什么?

解答

Class 组件

import React, { Component } from 'react';

class Counter extends Component {
  // 构造函数中初始化 state
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  // 生命周期方法
  componentDidMount() {
    console.log('组件已挂载');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('组件已更新');
  }

  componentWillUnmount() {
    console.log('组件将卸载');
  }

  // 方法需要绑定 this 或使用箭头函数
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>+1</button>
      </div>
    );
  }
}

函数组件

import React, { useState, useEffect } from 'react';

function Counter() {
  // useState 管理状态
  const [count, setCount] = useState(0);

  // useEffect 处理副作用,替代生命周期
  useEffect(() => {
    console.log('组件已挂载或更新');
    
    // 返回清理函数,相当于 componentWillUnmount
    return () => {
      console.log('清理副作用');
    };
  }, [count]); // 依赖数组

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+1</button>
    </div>
  );
}

主要区别对比

特性Class 组件函数组件
语法ES6 class普通函数
状态管理this.state + setStateuseState
生命周期生命周期方法useEffect
this 绑定需要处理不需要
代码量较多较少
性能优化shouldComponentUpdate / PureComponentReact.memo / useMemo / useCallback

捕获 props 的差异

这是一个容易被忽略的重要区别:

// Class 组件 - this.props 可能在异步回调中变化
class ProfilePage extends Component {
  showMessage = () => {
    // 3 秒后读取的是最新的 props
    setTimeout(() => {
      alert('Followed ' + this.props.user);
    }, 3000);
  };

  render() {
    return <button onClick={this.showMessage}>Follow</button>;
  }
}

// 函数组件 - props 被闭包捕获,保持不变
function ProfilePage(props) {
  const showMessage = () => {
    // 3 秒后读取的是点击时的 props
    setTimeout(() => {
      alert('Followed ' + props.user);
    }, 3000);
  };

  return <button onClick={showMessage}>Follow</button>;
}

函数组件每次渲染都会捕获当前的 props 和 state,这种行为通常更符合预期。

关键点

  • 函数组件更简洁,没有 this 绑定问题
  • Hooks 让函数组件具备了 Class 组件的所有能力
  • 函数组件通过闭包捕获 props/state,Class 组件通过 this 读取最新值
  • 函数组件更容易做代码复用(自定义 Hooks)
  • React 官方推荐使用函数组件 + Hooks