useRef
操作DOM元素
//操作DOM元素
1.创建useRef对象
const 变量名(inputRef) = useRef(null)
2.操作绑定的DOM元素
const fn1 = ()=>{
//变量名(inputRef).current 获取绑定的DOM元素
变量名(inputRef).current.focus()
}
3.在DOM元素上绑定一下
<input type="text" ref={inputRef} />
//存储可变值 而不触发重新渲染
const countRef = useRef(0)
const [counts,setCounts] = useState(0)
const addCount=()=>{
countRef.current +=1
setCounts(prev=>prev+1)
}
{/* 用法2:可变值存储 */}
<div>
<h2>2. Mutable Value (Console Log)</h2>
<button onClick={incrementCount}>
Increment Count (Current: {countRef.current})
</button>
<p>Note: Check console for updates without re-rendering.</p>
</div>
跨组件调用
-
useRef:父组件创建引用对象,传递给子组件。const childRef = useRef(null); // 初始化ref -
forwardRef:子组件接收父组件的ref并绑定到内部元素或方法。const ChildComponent = forwardRef((props, ref) => { ... }); -
useImperativeHandle:子组件暴露特定的方法或属性给父组件调用。useImperativeHandle(ref, () => ({ method1: () => { ... }, method2: () => { ... } })); -
父组件通过
ref.current调用方法childRef.current.method1(); // 直接调用子组件方法
//跨组件调用
//父组件中
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
//1.创建对象
const childRef = useRef(null);
//接收子组件方法
const handleClick = () => {
childRef.current.sayHello(); // 调用子组件方法
console.log(childRef.current.getData()); // 获取子组件数据
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Call Child Method</button>
</div>
);
}
export default ParentComponent;
//ChildComponent.jsx(子组件)中
import React, { forwardRef, useImperativeHandle } from 'react';
// 接收父组件ref
const ChildComponent = forwardRef((props, ref) => {
// 暴露方法给父组件
useImperativeHandle(ref, () => ({
//绑定到内部元素
sayHello: () => {
alert("Hello from Child!");
},
getData: () => {
return "Data from Child";
}
}));
return <div>Child Component</div>;
});
export default ChildComponent;
useEffect
数据获取
- 使用
fetch请求数据,通过try/catch处理错误 - 空依赖数组
[]确保只在组件挂载时执行一次
定时器
-
setInterval每秒更新状态,返回清理函数clearInterval防止内存泄漏
DOM操作
-
useRef绑定输入框,focus()在挂载后自动触发
事件监听
- 监听
resize事件,返回清理函数移除监听
useMemo
每次渲染都重新计算会浪费性能==>使用useMemo缓存计算结果
非常适合用于那些计算成本较高且依赖于某些变量的场景
适用场景
-
复杂的计算逻辑:当需要执行复杂的计算逻辑,且这些计算依赖于某些变量时,使用
useMemo可以避免不必要的重复计算。 -
避免重复渲染子组件:当子组件依赖于父组件的某些计算结果时,使用
useMemo可以确保只有在依赖项发生变化时才重新计算,从而避免子组件的不必要渲染。 -
性能优化:在性能敏感的场景中,
useMemo可以显著减少计算开销,提高应用的响应速度。
useReducer
- useReducer接收两个参数: 第⼀个参数:reducer函数。第⼆个参数:初始化的state。 返回值为最新的state和dispatch函数(⽤于触发reducer函数,计算对应的 state)。
- 按照官⽅的说法:对于复杂的state操作逻辑,嵌套的state对象,推 荐使⽤useReducer。
基础用法:适合管理多个关联状态的场景
import React, { useReducer } from 'react';
// 定义 reducer 函数
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error('Unknown action type');
}
}
function Counter() {
// 初始化 useReducer
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
参数说明:
reducer:纯函数,根据 action.type 返回新状态。
initialState:状态的初始值(这里是 { count: 0 })。
返回值:
state:当前状态。
dispatch:触发状态更新的函数(调用时会传入 action 对象