列举react中类组件和函数组件常用到的方法

一、类组件(Class Component)常用函数/方法

1. 生命周期方法

方法名 调用时机 作用
constructor(props) 组件初始化时 初始化 state 或绑定 this(如事件处理函数)
static getDerivedStateFromProps(props, state) 父组件重新渲染时 根据 props 更新 state(较少使用)
render() 每次 state/props 变化时 返回 JSX,描述 UI 结构
componentDidMount() 组件挂载到 DOM 后 执行副作用(如数据请求、订阅事件)
shouldComponentUpdate(nextProps, nextState) 更新前触发 决定是否重新渲染(优化性能)
getSnapshotBeforeUpdate(prevProps, prevState) DOM 更新前 捕获 DOM 信息(如滚动位置)
componentDidUpdate(prevProps, prevState, snapshot) 组件更新后 执行副作用(如更新 DOM、发起新请求)
componentWillUnmount() 组件卸载前 清理副作用(如取消订阅、清除定时器)

二、函数组件(Functional Component)常用函数/方法

函数组件基于 Hooks 实现状态和副作用管理,更简洁且无生命周期概念。

1. 核心 Hooks

Hook 作用 示例
useState 管理组件状态 const [count, setCount] = useState(0);
useEffect 处理副作用(类似 componentDidMount/componentDidUpdate/componentWillUnmount jsx<br>useEffect(() => {<br> console.log("Mounted or updated");<br> return () => console.log("Unmounted");<br>}, [deps]);<br>
useContext 访问 Context 数据 const value = useContext(MyContext);
useReducer 复杂状态逻辑(类似 Redux) const [state, dispatch] = useReducer(reducer, initialState);
useRef 获取 DOM 引用或存储可变值 const inputRef = useRef(null);
useMemo 缓存计算结果(优化性能) const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useCallback 缓存函数(避免不必要的重新渲染) const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
相关推荐
IT_陈寒41 分钟前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰1 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
山河木马2 小时前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林8182 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花2 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu12273 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
咪库咪库咪3 小时前
Vue3-生命周期
前端
莪_幻尘4 小时前
你的 AI Skill 越多越蠢?Token 上下文爆炸的求生指南
前端·ai编程
lichenyang4534 小时前
从 has.echo 到异步 API 注册表:一次 ASCF API 回调不触发的排查复盘
前端
林瞅瞅4 小时前
Nuxt3 项目部署 Nginx 防盗链后特定 JS 文件 403 问题修复方案
前端