函数组件和类组件的区别是什么?
满分答案#
函数组件使用 Hooks 管理状态与副作用,代码更简洁、逻辑更易复用;类组件使用 class、this、生命周期,代码冗余且难以优化。 React 官方推荐函数组件,未来趋势完全以函数组件为主。
一、核心区别(最清晰对比)#
1. 编写方式#
- 函数组件:普通 JS 函数,返回 JSX
- 类组件:继承
React.Component的 class,必须写render()
2. 状态管理#
- 函数组件:
useState/useReducer - 类组件:
this.state/this.setState
3. 副作用/生命周期#
- 函数组件:
useEffect统一管理 - 类组件:
componentDidMount/update/unmount
4. this 指向#
- 函数组件:没有 this,完全不用管
- 类组件:必须处理 this 绑定,容易出 bug
5. 逻辑复用#
- 函数组件:自定义 Hooks,完美复用
- 类组件:高阶组件、render-props,嵌套复杂
6. 性能 & 未来#
- 函数组件:轻量、易编译、React 未来主推
- 类组件:相对笨重,未来会逐步减少使用
二、最直观代码对比#
函数组件(简洁)#
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
// 逻辑
}, []);
return <div>{count}</div>
}jsx类组件(繁琐)#
class App extends React.Component {
constructor() {
super();
this.state = { count: 0 };
}
componentDidMount() {}
componentDidUpdate() {}
componentWillUnmount() {}
render() {
return <div>{this.state.count}</div>
}
}jsx三、满分总结#
- 函数组件是函数,类组件是 class;
- 函数组件用 Hooks 管理状态,类组件用 this.state;
- 函数组件无 this,类组件必须处理 this 指向;
- 函数组件逻辑复用靠自定义 Hooks,类组件靠高阶组件;
- 函数组件代码更简洁、性能更好,是 React 官方未来标准。
一句话记住#
函数组件 = 简洁 + Hooks + 无this + 未来主流 类组件 = 繁琐 + 生命周期 + this + 逐步淘汰