React中Class 组件 vs Hooks 对照

1、Class 组件 vs Hooks 对照

类组件生命周期 Hooks 对应写法 说明
componentDidMount useEffect(() => { ... }, []) 组件挂载时执行一次
componentDidUpdate useEffect(() => { ... }, [deps]) 依赖项变化时执行
componentWillUnmount useEffect(() => { return () => {...} }, []) 卸载时执行清理逻辑

2、 示例代码

1. Class 组件写法

bash 复制代码
import React from 'react';

class Child extends React.Component {
  componentDidMount() {
    console.log("挂载完成 componentDidMount");
  }

  componentDidUpdate() {
    console.log("更新完成 componentDidUpdate");
  }

  componentWillUnmount() {
    console.log("卸载 componentWillUnmount");
  }

  render() {
    return <div>计数:{this.props.count}</div>;
  }
}

2. Hooks 写法(函数组件)

import React, { useEffect } from 'react';

function Child({ count }) {

// 模拟 componentDidMount + componentWillUnmount

useEffect(() => {

console.log("挂载完成 (相当于 componentDidMount)");

复制代码
return () => {
  console.log("卸载 (相当于 componentWillUnmount)");
};

}, []); // 空依赖 → 只在挂载和卸载时运行

// 模拟 componentDidUpdate

useEffect(() => {

console.log("更新完成 (相当于 componentDidUpdate),count=", count);

}, [count]); // count 变化时触发

return
计数:{count}
;
}

3、总结

componentDidMount → useEffect(() => {...}, [])

componentDidUpdate → useEffect(() => {...}, [依赖])

componentWillUnmount → useEffect 的 清理函数

👉 所以在 Hooks 中,所有生命周期逻辑都通过 useEffect 来表达,只是依赖数组的不同决定了它模拟哪一个生命周期。

相关推荐
wangbing112529 分钟前
layui窗口标题
前端·javascript·layui
qq_3985865440 分钟前
Utools插件实现Web Bluetooth
前端·javascript·electron·node·web·web bluetooth
李剑一1 小时前
mitt和bus有什么区别
前端·javascript·vue.js
VisuperviReborn1 小时前
React Native 与 iOS 原生通信:从理论到实践
前端·react native·前端框架
hashiqimiya1 小时前
html的input的required
java·前端·html
soda_yo1 小时前
JavaScripe中你所不知道的"变量提升"
javascript
Mapmost1 小时前
WebGL三维模型标准(二)模型加载常见问题解决方案
前端
Mapmost1 小时前
Web端三维模型标准(一):单位与比例、多边形优化
前端
www_stdio1 小时前
JavaScript 执行机制详解:从 V8 引擎到执行上下文
前端·javascript
我命由我123452 小时前
HTML - 换行标签的 3 种写法(<br>、<br/>、<br />)
前端·javascript·css·html·css3·html5·js