列举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]);
相关推荐
玉宇夕落6 分钟前
React 父子组件通信 Todo List 看透单向数据流与不可变数据
前端
软件开发技术深度爱好者6 分钟前
国际音标魔法实验室工具HTML5实现
前端·html5·英语学习
FogLetter8 分钟前
嘘!WebSocket正在“偷听”你的网络请求——全双工通信的魔法
前端·面试
用户938515635078 分钟前
从零构建 React Todo 应用:组件化设计与数据流深度解析
前端·javascript
IT_陈寒11 分钟前
Python线程池把我坑惨了,这些盲区你不踩?
前端·人工智能·后端
mONESY15 分钟前
从 DeepSeek WebGPU 输入框,吃透 React+TS 四大核心开发实践
javascript·后端
程序员爱钓鱼36 分钟前
第一个 Go 程序:Hello World
前端·后端·go
阳光是sunny39 分钟前
LangGraph 核心概念详解:从编译到可视化
前端·人工智能·后端
寒水馨1 小时前
macOS下载、安装electron-v43.2.0(附安装包electron-v43.2.0-darwin-arm64.zip)
javascript·macos·electron·node.js·跨平台·桌面应用开发·开源框架
不好听6131 小时前
React 父子组件通信:从 Todo 应用理解单向数据流
前端·react.js