列举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]);
相关推荐
Data_Journal9 小时前
【无标题】
大数据·服务器·前端·数据库·人工智能
我爱加班、、9 小时前
new Map()+Array.from()整理elementPlus的级联器数据
linux·前端·javascript
Hx_Ma169 小时前
Map集合的5种遍历方式
java·前端·javascript
css趣多多9 小时前
render函数
前端·javascript·vue.js
web打印社区9 小时前
前端开发实现PDF打印需求:从基础方案到专业解决方案
前端·vue.js·react.js·electron·pdf
时光追逐者9 小时前
使用 MWGA 帮助 7 万行 Winforms 程序快速迁移到 WEB 前端
前端·c#·.net
搬砖的阿wei9 小时前
CSS常用选择器总结
前端·css
2601_9498333910 小时前
flutter_for_openharmony口腔护理app实战+意见反馈实现
android·javascript·flutter
摘星编程10 小时前
OpenHarmony环境下React Native:自定义useFieldArray字段数组
react native·react.js·harmonyos
Trae1ounG10 小时前
Vue Iframe
前端·javascript·vue.js