React 18变量管理:从useState到useRef的7种实战场景解析
在React 18的函数组件开发中,变量管理看似简单,实则暗藏玄机。很多开发者在使用useState、useRef和普通变量时,常常陷入选择困境:这个数据该用哪种方式存储?为什么我的组件渲染次数这么多?为什么有些值在事件处理函数中总是“滞后”?
这些问题背后,其实是React变量管理机制的理解深度问题。今天我们就来深入探讨React函数组件中的7种变量管理场景,从基础用法到高级优化,帮你彻底理清思路。无论你是React新手还是有一定经验的开发者,这篇文章都将为你提供实用的代码模板和性能优化建议。
1. 理解React变量管理的三大支柱
在深入具体场景之前,我们需要先建立对React变量管理三大支柱的清晰认知。这三种方式各有其适用场景,理解它们的差异是写出高效React代码的基础。
1.1 普通变量:每次渲染都重新创建
普通变量是JavaScript中最基础的存储方式,在React函数组件中,它们的行为有一个关键特点:每次组件重新渲染时,普通变量都会被重新创建和初始化。
function Counter() {
// 每次渲染都会重新创建和初始化
const localCount = 0;
const handleClick = () => {
// 这里的修改不会触发重新渲染
// 而且下次渲染时localCount又会变回0
console.log(localCount); // 总是0
};
return <button onClick={handleClick}>点击</button>;
}
注意:普通变量适合存储那些不需要在渲染间保持的临时数据,比如计算过程中的中间值,或者只在当前渲染周期内有效的变量。
1.2 useState:响应式状态管理
useState是React中最常用的状态管理Hook,它的核心特点是状态变化会触发组件重新渲染。
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
// 调用setCount会触发组件重新渲染
setCount(prev => prev + 1);
};
return (
<div>
<p>当前计数: {count}</p>
<button onClick={handleClick}>增加</button>
</div>
);
}
useState的工作原理:
- React会在组件首次渲染时创建状态值
- 每次调用setter函数时,React会安排一次重新渲染
- 在重新渲染时,useState会返回更新后的状态值
1.3 useRef:持久化引用
useRef创建的引用对象在组件的整个生命周期中保持不变,修改ref.current不会触发重新渲染。
function Timer() {
const intervalRef = useRef(null);
const [seconds, setSeconds] = useState(0);
const startTimer = () => {
// 存储interval ID,不会触发重新渲染
intervalRef.current = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
};
const stopTimer = () => {
clearInterval(intervalRef.current);
};
return (
<div>
<p>时间: {seconds}秒</p>
<button onClick={startTimer}>开始</button>
<button onClick={stopTimer}>停止</button>
</div>
);
}
三种方式的对比表格:
| 特性 | 普通变量 | useState | useRef |
|---|---|---|---|
| 生命周期 | 每次渲染重新创建 | 跨渲染保持 | 跨渲染保持 |
| 修改触发渲染 | 否 | 是 | 否 |
| 适合场景 | 临时计算、中间值 | UI相关状态 | DOM引用、计时器ID等 |
| 访问方式 | 直接访问 | 通过状态变量 | 通过ref.current |
| 更新方式 | 直接赋值 | 通过setter函数 | 直接修改current |
2. 表单控制:何时用状态,何时用引用?
表单处理是React开发中最常见的场景之一。不同的表单需求需要不同的变量管理策略。
2.1 受控组件:完全由状态驱动
受控组件是React推荐的表单处理方式,表单数据完全由React状态管理。
function ControlledForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('提交的数据:', formData);
};
return (
<form onSubmit={handleSubmit}>
<input
name="username"
value={formData.username}
onChange={handleChange}
placeholder="用户名"
/>
<input
name="email"
type="email"
value={formData.email}
onChange={handleChange}
placeholder="邮箱"
/>
<input
name="password"
type="password"
value={formData.password}
onChange={handleChange}
placeholder="密码"
/>
<button type="submit">提交</button>
</form>
);
}
受控组件的优势:
- 即时验证:可以在每次输入时进行实时验证
- 即时格式化:可以实时格式化输入内容
- 完全控制:表单状态完全由React管理
2.2 非受控组件:使用ref获取表单数据
在某些场景下,非受控组件可能更合适,特别是当表单数据只在提交时需要,或者表单非常复杂时。
function UncontrolledForm() {
const formRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(formRef.current);
const data = Object.fromEntries(formData.entries());
console.log('提交的数据:', data);
};
return (
<form ref={formRef} onSubmit={handleSubmit}>
<input name="username" placeholder="用户名" />
<input name="email" type="email" placeholder="邮箱" />
<input name="password" type="password" placeholder="密码" />
<button type="submit">提交</button>
</form>
);
}
2.3 混合模式:状态与引用结合
在实际开发中,我们经常需要混合使用状态和引用来优化性能。
function OptimizedForm() {
const [formData, setFormData] = useState({
username: '',
email: ''
});
// 使用ref存储不需要即时验证的字段
const passwordRef = useRef('');
const handleChange = (e) => {
const { name, value } = e.target;
if (name === 'password') {
// 密码字段使用ref,避免不必要的渲染
passwordRef.current = value;
} else {
// 其他字段使用状态,需要即时验证
setFormData(prev => ({
...prev,
[name]: value
}));
}
};
const handleSubmit = (e) => {
e.preventDefault();
const submitData = {
...formData,
password: passwordRef.current
};
console.log('提交的数据:', submitData);
};
return (
<form onSubmit={handleSubmit}>
<input
name="username"
value={formData.username}
onChange={handleChange}
placeholder="用户名"
/>
<input
name="email"
type="email"
value={formData.email}
onChange={handleChange}
placeholder="邮箱"
/>
<input
name="password"
type="password"
onChange={handleChange}
placeholder="密码"
/>
<button type="submit">提交</button>
</form>
);
}
表单处理的选择策略:
| 场景 | 推荐方案 | 理由 |
|---|---|---|
| 需要即时验证 | 受控组件(useState) | 每次输入都能触发验证逻辑 |
| 需要即时格式化 | 受控组件(useState) | 实时格式化输入内容 |
| 复杂表单,性能敏感 | 非受控组件(useRef) | 减少不必要的重新渲染 |
| 只在提交时需要数据 | 非受控组件(useRef) | 避免输入过程中的状态更新 |
| 部分字段需要验证 | 混合模式 | 平衡性能与功能需求 |
3. 动画与性能优化:避免不必要的渲染
在动画和高频更新的场景中,性能优化尤为重要。不当的状态管理会导致严重的性能问题。
3.1 动画帧优化:使用ref避免状态更新
对于需要高频更新的动画,使用useState会导致大量不必要的重新渲染。
function SmoothAnimation() {
const [position, setPosition] = useState(0);
const animationRef = useRef(null);
const requestRef = useRef();
const startTimeRef = useRef();
const animate = (timestamp) => {
if (!startTimeRef.current) {
startTimeRef.current = timestamp;
}
const elapsed = timestamp - startTimeRef.current;
// 直接修改ref,不触发渲染
animationRef.current.style.transform = `translateX(${elapsed / 10}px)`;
if (elapsed < 2000) { // 动画持续2秒
requestRef.current = requestAnimationFrame(animate);
}
};
const startAnimation = () => {
startTimeRef.current = null;
requestRef.current = requestAnimationFrame(animate);
};
const stopAnimation = () => {
if (requestRef.current) {
cancelAnimationFrame(requestRef.current);
}
};
useEffect(() => {
return () => {
if (requestRef.current) {
cancelAnimationFrame(requestRef.current);
}
};
}, []);
return (
<div>
<div
ref={animationRef}
style={{
width: '50px',
height: '50px',
backgroundColor: 'blue'
}}
/>
<button onClick={startAnimation}>开始动画</button>
<button onClick={stopAnimation}>停止动画</button>
</div>
);
}
3.2 防抖与节流:使用ref存储定时器
在处理用户输入等高频事件时,防抖和节流是常用的优化手段。
function SearchInput() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const timeoutRef = useRef(null);
const searchAPI = async (searchQuery) => {
// 模拟API调用
const mockResults = [
`结果1: ${searchQuery}`,
`结果2: ${searchQuery}`,
`结果3: ${searchQuery}`
];
setResults(mockResults);
};
const handleInputChange = (e) => {
const value = e.target.value;
setQuery(value);
// 清除之前的定时器
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// 设置新的防抖定时器
timeoutRef.current = setTimeout(() => {
if (value.trim()) {
searchAPI(value);
}
}, 300); // 300ms防抖
};
useEffect(() => {
return () => {
// 组件卸载时清理定时器
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return (
<div>
<input
type="text"
value={query}
onChange={handleInputChange}
placeholder="搜索..."
/>
<ul>
{results.map((result, index) => (
<li key={index}>{result}</li>
))}
</ul>
</div>
);
}
3.3 性能敏感的计算:使用useMemo和useCallback
对于计算量大的操作,可以使用useMemo和useCallback来避免不必要的重复计算。
function ExpensiveCalculation() {
const [count, setCount] = useState(0);
const [input, setInput] = useState('');
// 使用useMemo缓存计算结果
const expensiveResult = useMemo(() => {
console.log('执行昂贵计算...');
let result = 0;
for (let i = 0; i < 1000000; i++) {
result += Math.sqrt(i) * Math.sin(i);
}
return result + count;
}, [count]); // 只有当count变化时才重新计算
// 使用useCallback缓存函数
const handleClick = useCallback(() => {
console.log('当前计数:', count);
setCount(prev => prev + 1);
}, [count]);
return (
<div>
<p>计算结果: {expensiveResult}</p>
<p>计数: {count}</p>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="输入不会触发重新计算"
/>
<button onClick={handleClick}>增加计数</button>
</div>
);
}
动画与性能优化要点总结:
- 高频更新使用ref:对于requestAnimationFrame等高频更新,直接操作DOM而不是通过状态
- 定时器管理使用ref:存储定时器ID,确保能正确清理
- 防抖节流使用ref:存储上一次的定时器或时间戳
- 昂贵计算使用useMemo:避免不必要的重复计算
- 事件处理函数使用useCallback:避免子组件不必要的重新渲染
4. DOM操作与第三方库集成
当需要直接操作DOM或与第三方库(如图表库、地图库等)集成时,useRef是不可或缺的工具。
4.1 直接DOM操作
function CanvasDrawing() {
const canvasRef = useRef(null);
const [isDrawing, setIsDrawing] = useState(false);
const lastPositionRef = useRef({ x: 0, y: 0 });
const getCanvasContext = () => {
const canvas = canvasRef.current;
if (!canvas) return null;
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
return ctx;
};
const startDrawing = (e) => {
const rect = canvasRef.current.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
lastPositionRef.current = { x, y };
setIsDrawing(true);
};
const draw = (e) => {
if (!isDrawing) return;
const rect = canvasRef.current.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const ctx = getCanvasContext();
if (!ctx) return;
ctx.beginPath();
ctx.moveTo(lastPositionRef.current.x, lastPositionRef.current.y);
ctx.lineTo(x, y);
ctx.stroke();
lastPositionRef.current = { x, y };
};
const stopDrawing = () => {
setIsDrawing(false);
};
const clearCanvas = () => {
const ctx = getCanvasContext();
if (!ctx) return;
const canvas = canvasRef.current;
ctx.clearRect(0, 0, canvas.width, canvas.height);
};
return (
<div>
<canvas
ref={canvasRef}
width={800}
height={400}
style={{ border: '1px solid #ccc' }}
onMouseDown={startDrawing}
onMouseMove={draw}
onMouseUp={stopDrawing}
onMouseLeave={stopDrawing}
/>
<button onClick={clearCanvas}>清空画布</button>
</div>
);
}
4.2 第三方图表库集成
function ChartIntegration() {
const chartContainerRef = useRef(null);
const chartInstanceRef = useRef(null);
const [data, setData] = useState([30, 40, 35, 50, 49, 60]);
// 初始化图表
useEffect(() => {
if (!chartContainerRef.current) return;
// 模拟第三方图表库初始化
const ctx = chartContainerRef.current.getContext('2d');
// 这里使用模拟的图表对象
chartInstanceRef.current = {
ctx,
data: [...data],
update: function(newData) {
this.data = newData;
this.render();
},
render: function() {
// 模拟渲染逻辑
console.log('渲染图表数据:', this.data);
// 实际项目中这里会调用第三方库的渲染方法
},
destroy: function() {
// 清理资源
console.log('销毁图表实例');
}
};
chartInstanceRef.current.render();
// 清理函数
return () => {
if (chartInstanceRef.current) {
chartInstanceRef.current.destroy();
}
};
}, []); // 空依赖数组,只在挂载时执行一次
// 数据更新时更新图表
useEffect(() => {
if (chartInstanceRef.current) {
chartInstanceRef.current.update(data);
}
}, [data]);
const addDataPoint = () => {
const newValue = Math.floor(Math.random() * 100);
setData(prev => [...prev, newValue]);
};
return (
<div>
<canvas ref={chartContainerRef} width={600} height={300} />
<button onClick={addDataPoint}>添加数据点</button>
<div>
当前数据: {data.join(', ')}
</div>
</div>
);
}
4.3 视频播放器控制
function VideoPlayer() {
const videoRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
// 更新当前播放时间
useEffect(() => {
const video = videoRef.current;
if (!video) return;
const updateTime = () => {
setCurrentTime(video.currentTime);
};
video.addEventListener('timeupdate', updateTime);
video.addEventListener('loadedmetadata', () => {
setDuration(video.duration);
});
return () => {
video.removeEventListener('timeupdate', updateTime);
};
}, []);
const togglePlay = () => {
const video = videoRef.current;
if (!video) return;
if (video.paused) {
video.play();
setIsPlaying(true);
} else {
video.pause();
setIsPlaying(false);
}
};
const seek = (time) => {
const video = videoRef.current;
if (!video) return;
video.currentTime = time;
setCurrentTime(time);
};
const formatTime = (seconds) => {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
};
return (
<div>
<video
ref={videoRef}
width="600"
controls={false}
src="/path/to/video.mp4"
/>
<div>
<button onClick={togglePlay}>
{isPlaying ? '暂停' : '播放'}
</button>
<span>
{formatTime(currentTime)} / {formatTime(duration)}
</span>
</div>
<input
type="range"
min="0"
max={duration || 100}
value={currentTime}
onChange={(e) => seek(parseFloat(e.target.value))}
style={{ width: '100%' }}
/>
</div>
);
}
DOM操作与第三方库集成的最佳实践:
- 使用ref存储DOM引用:避免在每次渲染时重新获取DOM元素
- 在useEffect中初始化第三方库:确保DOM已经挂载
- 在清理函数中销毁资源:防止内存泄漏
- 使用ref存储第三方库实例:确保在整个组件生命周期中都能访问
- 将状态变化同步到第三方库:通过useEffect监听状态变化
5. 跨渲染周期保持数据一致性
在某些复杂场景中,我们需要确保数据在多个渲染周期中保持一致,或者需要在事件处理函数中访问最新的状态值。
5.1 使用ref存储最新状态
function RealTimeChat() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const messagesEndRef = useRef(null);
// 使用ref存储最新的消息列表
const latestMessagesRef = useRef(messages);
// 同步ref和state
useEffect(() => {
latestMessagesRef.current = messages;
}, [messages]);
// 模拟WebSocket连接
useEffect(() => {
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => {
const newMessage = JSON.parse(event.data);
// 使用ref中的最新值,避免闭包问题
setMessages(prev => [...prev, newMessage]);
};
return () => ws.close();
}, []);
const sendMessage = () => {
if (!input.trim()) return;
const newMessage = {
id: Date.now(),
text: input,
timestamp: new Date().toISOString()
};
// 立即更新本地状态
setMessages(prev => [...prev, newMessage]);
setInput('');
// 滚动到底部
scrollToBottom();
};
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// 模拟一个在定时器中访问最新消息的函数
useEffect(() => {
const interval = setInterval(() => {
// 这里可以安全地访问最新的消息
console.log('当前消息数量:', latestMessagesRef.current.length);
}, 5000);
return () => clearInterval(interval);
}, []);
return (
<div style={{ height: '400px', overflow: 'auto', border: '1px solid #ccc' }}>
{messages.map(msg => (
<div key={msg.id} style={{ padding: '8px', borderBottom: '1px solid #eee' }}>
<strong>{new Date(msg.timestamp).toLocaleTimeString()}</strong>
<div>{msg.text}</div>
</div>
))}
<div ref={messagesEndRef} />
<div style={{ position: 'sticky', bottom: 0, background: 'white', padding: '8px' }}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="输入消息..."
style={{ width: '80%', marginRight: '8px' }}
/>
<button onClick={sendMessage}>发送</button>
</div>
</div>
);
}
5.2 解决事件处理函数中的闭包问题
function CounterWithInterval() {
const [count, setCount] = useState(0);
const [isRunning, setIsRunning] = useState(false);
// 使用ref存储最新的count值
const countRef = useRef(count);
// 同步ref和state
useEffect(() => {
countRef.current = count;
}, [count]);
useEffect(() => {
let intervalId = null;
if (isRunning) {
intervalId = setInterval(() => {
// 使用ref中的值,避免闭包问题
console.log('当前计数:', countRef.current);
setCount(prev => prev + 1);
}, 1000);
}
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [isRunning]); // 只依赖isRunning
return (
<div>
<p>计数: {count}</p>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? '停止' : '开始'}
</button>
<button onClick={() => {
setCount(0);
console.log('重置后计数:', countRef.current);
}}>
重置
</button>
</div>
);
}
5.3 表单草稿保存功能
function DraftForm() {
const [formData, setFormData] = useState({
title: '',
content: '',
tags: []
});
const draftTimerRef = useRef(null);
const lastSavedRef = useRef(null);
// 自动保存草稿
const autoSaveDraft = useCallback(() => {
if (draftTimerRef.current) {
clearTimeout(draftTimerRef.current);
}
draftTimerRef.current = setTimeout(() => {
// 保存到localStorage
localStorage.setItem('draft', JSON.stringify(formData));
lastSavedRef.current = new Date();
console.log('草稿已保存:', formData);
}, 1000); // 1秒后保存
}, [formData]);
const handleChange = (field, value) => {
setFormData(prev => ({
...prev,
[field]: value
}));
};
// 监听表单变化,触发自动保存
useEffect(() => {
autoSaveDraft();
}, [formData, autoSaveDraft]);
// 恢复草稿
useEffect(() => {
const savedDraft = localStorage.getItem('draft');
if (savedDraft) {
try {
const parsed = JSON.parse(savedDraft);
setFormData(parsed);
lastSavedRef.current = new Date();
} catch (error) {
console.error('恢复草稿失败:', error);
}
}
}, []);
// 清理定时器
useEffect(() => {
return () => {
if (draftTimerRef.current) {
clearTimeout(draftTimerRef.current);
}
};
}, []);
const getLastSavedTime = () => {
if (!lastSavedRef.current) return '从未保存';
const now = new Date();
const diff = now - lastSavedRef.current;
const seconds = Math.floor(diff / 1000);
if (seconds < 60) return `${seconds}秒前`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟前`;
return `${Math.floor(seconds / 3600)}小时前`;
};
return (
<div>
<div style={{ marginBottom: '16px', color: '#666' }}>
最后保存: {getLastSavedTime()}
</div>
<div style={{ marginBottom: '16px' }}>
<input
value={formData.title}
onChange={(e) => handleChange('title', e.target.value)}
placeholder="标题"
style={{ width: '100%', padding: '8px' }}
/>
</div>
<div style={{ marginBottom: '16px' }}>
<textarea
value={formData.content}
onChange={(e) => handleChange('content', e.target.value)}
placeholder="内容"
style={{ width: '100%', height: '200px', padding: '8px' }}
/>
</div>
<button
onClick={() => {
localStorage.removeItem('draft');
setFormData({ title: '', content: '', tags: [] });
lastSavedRef.current = null;
}}
style={{ marginRight: '8px' }}
>
清除草稿
</button>
<button
onClick={() => {
console.log('发布内容:', formData);
localStorage.removeItem('draft');
}}
>
发布
</button>
</div>
);
}
跨渲染周期数据一致性的关键技巧:
- 使用ref存储最新状态:解决事件处理函数和定时器中的闭包问题
- 在useEffect中同步ref和state:确保ref始终持有最新值
- 清理定时器和事件监听器:防止内存泄漏
- 使用useCallback缓存函数:避免不必要的重新创建
- 合理使用localStorage:持久化重要数据
6. 条件渲染与变量作用域
条件渲染是React中的常见模式,但不同的条件渲染方式会影响变量的作用域和生命周期。
6.1 条件渲染中的变量作用域
function ConditionalRendering() {
const [showDetails, setShowDetails] = useState(false);
const [user, setUser] = useState(null);
// 这个变量在每次渲染时都会重新创建
const renderTimestamp = new Date().toLocaleTimeString();
// 使用useRef保持跨渲染的值
const mountTimeRef = useRef(new Date().toLocaleTimeString());
// 模拟数据加载
useEffect(() => {
const timer = setTimeout(() => {
setUser({
id: 1,
name: '张三',
email: 'zhangsan@example.com'
});
}, 1000);
return () => clearTimeout(timer);
}, []);
const toggleDetails = () => {
setShowDetails(!showDetails);
};
// 条件渲染中的变量
let detailsContent = null;
if (showDetails && user) {
// 这个变量只在条件满足时存在
const detailInfo = `用户ID: ${user.id}, 邮箱: ${user.email}`;
detailsContent = (
<div style={{ marginTop: '16px', padding: '16px', background: '#f5f5f5' }}>
<p>{detailInfo}</p>
<p>详情渲染时间: {new Date().toLocaleTimeString()}</p>
</div>
);
}
return (
<div>
<p>组件挂载时间: {mountTimeRef.current}</p>
<p>当前渲染时间: {renderTimestamp}</p>
{user ? (
<div>
<h3>欢迎, {user.name}</h3>
<button onClick={toggleDetails}>
{showDetails ? '隐藏详情' : '显示详情'}
</button>
{detailsContent}
</div>
) : (
<p>加载用户信息中...</p>
)}
{/* 使用&&运算符的条件渲染 */}
{user && !showDetails && (
<p style={{ color: '#666', fontSize: '14px' }}>
点击按钮查看用户详情
</p>
)}
{/* 使用三元运算符的条件渲染 */}
<div style={{ marginTop: '16px' }}>
{user ? (
<button onClick={() => setUser(null)}>注销</button>
) : (
<button onClick={() => setUser({ id: 1, name: '张三' })}>登录</button>
)}
</div>
</div>
);
}
6.2 条件渲染的性能优化
function OptimizedConditionalRender() {
const [activeTab, setActiveTab] = useState('home');
const [data, setData] = useState(null);
// 使用useMemo缓存计算结果
const processedData = useMemo(() => {
if (!data) return null;
console.log('处理数据中...');
// 模拟昂贵的计算
return {
...data,
processed: true,
timestamp: new Date().toISOString()
};
}, [data]);
// 使用useCallback缓存事件处理函数
const fetchHomeData = useCallback(async () => {
console.log('获取首页数据...');
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 500));
setData({ type: 'home', content: '首页内容' });
}, []);
const fetchProfileData = useCallback(async () => {
console.log('获取个人资料数据...');
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 500));
setData({ type: 'profile', content: '个人资料内容' });
}, []);
const fetchSettingsData = useCallback(async () => {
console.log('获取设置数据...');
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 500));
setData({ type: 'settings', content: '设置内容' });
}, []);
// 根据activeTab选择要渲染的组件
const renderContent = () => {
switch (activeTab) {
case 'home':
return <HomeTab data={processedData} fetchData={fetchHomeData} />;
case 'profile':
return <ProfileTab data={processedData} fetchData={fetchProfileData} />;
case 'settings':
return <SettingsTab data={processedData} fetchData={fetchSettingsData} />;
default:
return <div>未知标签页</div>;
}
};
return (
<div>
<div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
{['home', 'profile', 'settings'].map(tab => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
style={{
padding: '8px 16px',
background: activeTab === tab ? '#007bff' : '#f8f9fa',
color: activeTab === tab ? 'white' : '#333',
border: '1px solid #dee2e6',
borderRadius: '4px',
cursor: 'pointer'
}}
>
{tab === 'home' ? '首页' :
tab === 'profile' ? '个人资料' : '设置'}
</button>
))}
</div>
<div style={{ padding: '16px', border: '1px solid #dee2e6', borderRadius: '4px' }}>
{renderContent()}
</div>
</div>
);
}
// 子组件
const HomeTab = React.memo(({ data, fetchData }) => {
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<div>
<h3>首页</h3>
{data ? (
<p>{data.content} - 处理时间: {data.timestamp}</p>
) : (
<p>加载中...</p>
)}
</div>
);
});
const ProfileTab = React.memo(({ data, fetchData }) => {
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<div>
<h3>个人资料</h3>
{data ? (
<p>{data.content} - 处理时间: {data.timestamp}</p>
) : (
<p>加载中...</p>
)}
</div>
);
});
const SettingsTab = React.memo(({ data, fetchData }) => {
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<div>
<h3>设置</h3>
{data ? (
<p>{data.content} - 处理时间: {data.timestamp}</p>
) : (
<p>加载中...</p>
)}
</div>
);
});
6.3 条件渲染的模式对比
function RenderingPatterns() {
const [status, setStatus] = useState('idle'); // idle, loading, success, error
const [data, setData] = useState(null);
const [error, setError] = useState(null);
// 模式1:提前返回
if (status === 'loading') {
return (
<div style={{ padding: '40px', textAlign: 'center' }}>
<div>加载中...</div>
<button onClick={() => setStatus('idle')}>取消</button>
</div>
);
}
// 模式2:变量赋值
let content = null;
if (status === 'success' && data) {
content = (
<div>
<h3>数据加载成功</h3>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
} else if (status === 'error') {
content = (
<div style={{ color: 'red' }}>
<h3>加载失败</h3>
<p>{error?.message || '未知错误'}</p>
</div>
);
}
// 模式3:三元运算符
const statusText = status === 'idle' ? '准备加载' :
status === 'loading' ? '加载中' :
status === 'success' ? '加载成功' : '加载失败';
// 模式4:逻辑与运算符
const showRetryButton = status === 'error' || status === 'success';
const loadData = async () => {
setStatus('loading');
setError(null);
try {
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 1000));
// 模拟随机成功/失败
const isSuccess = Math.random() > 0.3;
if (isSuccess) {
setData({
id: 1,
name: '示例数据',
items: ['项目1', '项目2', '项目3'],
timestamp: new Date().toISOString()
});
setStatus('success');
} else {
throw new Error('模拟的API错误');
}
} catch (err) {
setError(err);
setStatus('error');
}
};
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>条件渲染模式示例</h2>
<div style={{ marginBottom: '20px' }}>
<p>当前状态: <strong>{statusText}</strong></p>
<div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
<button onClick={loadData} disabled={status === 'loading'}>
加载数据
</button>
{showRetryButton && (
<button onClick={loadData}>
重试
</button>
)}
<button onClick={() => {
setStatus('idle');
setData(null);
setError(null);
}}>
重置
</button>
</div>
</div>
{/* 使用变量赋值的内容 */}
{content}
{/* 模式5:立即执行函数 */}
{(() => {
if (status === 'idle') {
return (
<div style={{
padding: '20px',
background: '#f8f9fa',
borderRadius: '8px',
textAlign: 'center'
}}>
<p>点击"加载数据"按钮开始</p>
<small style={{ color: '#666' }}>
这个区块使用立即执行函数进行条件渲染
</small>
</div>
);
}
return null;
})()}
{/* 模式6:组件化条件渲染 */}
<StatusMessage status={status} data={data} error={error} />
</div>
);
}
// 模式6:组件化条件渲染
const StatusMessage = React.memo(({ status, data, error }) => {
// 使用switch语句处理多种状态
switch (status) {
case 'loading':
return <LoadingMessage />;
case 'success':
return <SuccessMessage data={data} />;
case 'error':
return <ErrorMessage error={error} />;
case 'idle':
default:
return <IdleMessage />;
}
});
const LoadingMessage = () => (
<div style={{
padding: '20px',
background: '#fff3cd',
border: '1px solid #ffeaa7',
borderRadius: '8px',
textAlign: 'center'
}}>
<div style={{ display: 'inline-block', marginRight: '10px' }}>
<div style={{
width: '20px',
height: '20px',
border: '3px solid #f1c40f',
borderTopColor: 'transparent',
borderRadius: '50%',
animation: 'spin 1s linear infinite'
}} />
</div>
数据加载中...
</div>
);
const SuccessMessage = ({ data }) => (
<div style={{
padding: '20px',
background: '#d1ecf1',
border: '1px solid #bee5eb',
borderRadius: '8px'
}}>
<h4 style={{ color: '#0c5460', marginTop: 0 }}>🎉 数据加载成功!</h4>
<div style={{
background: 'white',
padding: '10px',
borderRadius: '4px',
fontFamily: 'monospace',
fontSize: '14px',
overflowX: 'auto'
}}>
{JSON.stringify(data, null, 2)}
</div>
</div>
);
const ErrorMessage = ({ error }) => (
<div style={{
padding: '20px',
background: '#f8d7da',
border: '1px solid #f5c6cb',
borderRadius: '8px',
color: '#721c24'
}}>
<h4 style={{ marginTop: 0 }}>❌ 加载失败</h4>
<p>{error?.message || '未知错误发生'}</p>
<small>请检查网络连接后重试</small>
</div>
);
const IdleMessage = () => (
<div style={{
padding: '20px',
background: '#e2e3e5',
border: '1px solid #d6d8db',
borderRadius: '8px',
color: '#383d41',
textAlign: 'center'
}}>
<p style={{ margin: 0 }}>👆 点击上方按钮加载数据</p>
</div>
);
// 添加旋转动画
const style = document.createElement('style');
style.textContent = `
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
条件渲染的最佳实践总结:
- 简单条件使用&&或三元运算符:对于简单的显示/隐藏,使用逻辑与或三元运算符
- 复杂条件使用变量赋值:对于多个分支的条件,使用变量赋值提高可读性
- 提前返回简化逻辑:对于加载状态、错误状态等,可以提前返回
- 组件化复杂条件:将复杂的条件渲染逻辑提取为独立组件
- 使用useMemo优化计算:避免在每次渲染时重复计算
- 使用React.memo优化子组件:避免不必要的重新渲染
7. 高级模式:自定义Hook封装变量逻辑
当相同的变量管理逻辑在多个组件中重复出现时,可以将其封装为自定义Hook,提高代码复用性。
7.1 封装表单处理逻辑
// useForm.js - 自定义表单Hook
function useForm(initialValues = {}, validateFn = null) {
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState({});
const [touched, setTouched] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
// 使用ref存储最新的值,用于验证等场景
const valuesRef = useRef(values);
// 同步ref和state
useEffect(() => {
valuesRef.current = values;
}, [values]);
const handleChange = useCallback((name, value) => {
setValues(prev => ({
...prev,
[name]: value
}));
// 如果字段被触摸过,立即验证
if (touched[name]) {
if (validateFn) {
const newErrors = validateFn({ ...values, [name]: value });
setErrors(prev => ({
...prev,
[name]: newErrors[name] || ''
}));
}
}
}, [touched, validateFn, values]);
const handleBlur = useCallback((name) => {
setTouched(prev => ({
...prev,
[name]: true
}));
// 字段失去焦点时验证
if (validateFn) {
const newErrors = validateFn(valuesRef.current);
setErrors(prev => ({
...prev,
[name]: newErrors[name] || ''
}));
}
}, [validateFn]);
const setFieldValue = useCallback((name, value) => {
handleChange(name, value);
}, [handleChange]);
const setFieldTouched = useCallback((name, isTouched = true) => {
setTouched(prev => ({
...prev,
[name]: isTouched
}));
}, []);
const resetForm = useCallback(() => {
setValues(initialValues);
setErrors({});
setTouched({});
setIsSubmitting(false);
}, [initialValues]);
const submitForm = useCallback(async (onSubmit) => {
setIsSubmitting(true);
try {
// 验证所有字段
if (validateFn) {
const validationErrors = validateFn(valuesRef.current);
setErrors(validationErrors);
// 如果有错误,标记所有字段为已触摸
const hasErrors = Object.values(validationErrors).some(error => error);
if (hasErrors) {
const allTouched = {};
Object.keys(valuesRef.current).forEach(key => {
allTouched[key] = true;
});
setTouched(allTouched);
throw new Error('表单验证失败');
}
}
await onSubmit(valuesRef.current);
} catch (error) {
console.error('表单提交失败:', error);
throw error;
} finally {
setIsSubmitting(false);
}
}, [validateFn]);
return {
values,
errors,
touched,
isSubmitting,
handleChange,
handleBlur,
setFieldValue,
setFieldTouched,
resetForm,
submitForm,
isValid: Object.values(errors).every(error => !error)
};
}
// 使用示例
function UserForm() {
const validate = useCallback((values) => {
const errors = {};
if (!values.username) {
errors.username = '用户名不能为空';
} else if (values.username.length < 3) {
errors.username = '用户名至少3个字符';
}
if (!values.email) {
errors.email = '邮箱不能为空';
} else if (!/\S+@\S+\.\S+/.test(values.email)) {
errors.email = '邮箱格式不正确';
}
if (!values.password) {
errors.password = '密码不能为空';
} else if (values.password.length < 6) {
errors.password = '密码至少6个字符';
}
return errors;
}, []);
const {
values,
errors,
touched,
isSubmitting,
handleChange,
handleBlur,
resetForm,
submitForm,
isValid
} = useForm({
username: '',
email: '',
password: ''
}, validate);
const handleSubmit = async (formValues) => {
console.log('提交表单:', formValues);
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 1000));
alert('表单提交成功!');
resetForm();
};
return (
<form
onSubmit={(e) => {
e.preventDefault();
submitForm(handleSubmit);
}}
style={{ maxWidth: '400px', margin: '0 auto' }}
>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '4px' }}>
用户名
</label>
<input
type="text"
value={values.username}
onChange={(e) => handleChange('username', e.target.value)}
onBlur={() => handleBlur('username')}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${errors.username && touched.username ? '#dc3545' : '#ced4da'}`,
borderRadius: '4px'
}}
/>
{errors.username && touched.username && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '4px' }}>
{errors.username}
</div>
)}
</div>
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '4px' }}>
邮箱
</label>
<input
type="email"
value={values.email}
onChange={(e) => handleChange('email', e.target.value)}
onBlur={() => handleBlur('email')}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${errors.email && touched.email ? '#dc3545' : '#ced4da'}`,
borderRadius: '4px'
}}
/>
{errors.email && touched.email && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '4px' }}>
{errors.email}
</div>
)}
</div>
<div style={{ marginBottom: '24px' }}>
<label style={{ display: 'block', marginBottom: '4px' }}>
密码
</label>
<input
type="password"
value={values.password}
onChange={(e) => handleChange('password', e.target.value)}
onBlur={() => handleBlur('password')}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${errors.password && touched.password ? '#dc3545' : '#ced4da'}`,
borderRadius: '4px'
}}
/>
{errors.password && touched.password && (
<div style={{ color: '#dc3545', fontSize: '14px', marginTop: '4px' }}>
{errors.password}
</div>
)}
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<button
type="submit"
disabled={isSubmitting || !isValid}
style={{
padding: '10px 20px',
background: isValid ? '#007bff' : '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: isValid ? 'pointer' : 'not-allowed',
opacity: isSubmitting ? 0.7 : 1
}}
>
{isSubmitting ? '提交中...' : '提交'}
</button>
<button
type="button"
onClick={resetForm}
style={{
padding: '10px 20px',
background: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
重置
</button>
</div>
</form>
);
}
7.2 封装本地存储Hook
// useLocalStorage.js
function useLocalStorage(key, initialValue) {
// 使用ref存储值,避免在事件监听器中访问过期的闭包
const storedValueRef = useRef(null);
// 从localStorage读取初始值
const readValue = useCallback(() => {
if (typeof window === 'undefined') {
return initialValue;
}
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`读取localStorage键"${key}"时出错:`, error);
return initialValue;
}
}, [key, initialValue]);
const [storedValue, setStoredValue] = useState(() => {
const value = readValue();
storedValueRef.current = value;
return value;
});
// 同步ref和state
useEffect(() => {
storedValueRef.current = storedValue;
}, [storedValue]);
// 设置值的函数
const setValue = useCallback((value) => {
try {
// 允许值是一个函数(类似于useState)
const valueToStore = value instanceof Function ? value(storedValueRef.current) : value;
// 保存到state
setStoredValue(valueToStore);
// 保存到localStorage
if (typeof window !== 'undefined') {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
// 触发storage事件,让其他监听相同key的组件更新
if (typeof window !== 'undefined') {
window.dispatchEvent(
new StorageEvent('storage', {
key,
newValue: JSON.stringify(valueToStore)
})
);
}
} catch (error) {
console.warn(`设置localStorage键"${key}"时出错:`, error);
}
}, [key]);
// 清除值的函数
const removeValue = useCallback(() => {
try {
setStoredValue(initialValue);
if (typeof window !== 'undefined') {
window.localStorage.removeItem(key);
window.dispatchEvent(
new StorageEvent('storage', {
key,
newValue: null
})
);
}
} catch (error) {
console.warn(`移除localStorage键"${key}"时出错:`, error);
}
}, [key, initialValue]);
// 监听storage事件,实现跨标签页同步
useEffect(() => {
const handleStorageChange = (event) => {
if (event.key === key && event.newValue !== JSON.stringify(storedValueRef.current)) {
try {
const newValue = event.newValue ? JSON.parse(event.newValue) : initialValue;
setStoredValue(newValue);
storedValueRef.current = newValue;
} catch (error) {
console.warn(`处理storage事件时出错:`, error);
}
}
};
if (typeof window !== 'undefined') {
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}
}, [key, initialValue]);
return [storedValue, setValue, removeValue];
}
// 使用示例
function ThemeSwitcher() {
const [theme, setTheme, removeTheme] = useLocalStorage('theme', 'light');
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
};
const resetTheme = () => {
removeTheme();
};
return (
<div style={{
padding: '20px',
background: theme === 'dark' ? '#333' : '#fff',
color: theme === 'dark' ? '#fff' : '#333',
minHeight: '200px',
borderRadius: '8px',
transition: 'all 0.3s ease'
}}>
<h3>当前主题: {theme}</h3>
<p>这个主题偏好会保存在localStorage中,即使刷新页面或重新打开浏览器也会保留。</p>
<div style={{ display: 'flex', gap: '10px', marginTop: '20px' }}>
<button
onClick={toggleTheme}
style={{
padding: '10px 20px',
background: theme === 'dark' ? '#555' : '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
切换到{theme === 'light' ? '深色' : '浅色'}模式
</button>
<button
onClick={resetTheme}
style={{
padding: '10px 20px',
background: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
重置为默认
</button>
</div>
<div style={{ marginTop: '20px', fontSize: '14px', color: theme === 'dark' ? '#aaa' : '#666' }}>
<p>提示:</p>
<ul>
<li>尝试在另一个标签页中修改主题,这个页面会自动同步</li>
<li>刷新页面或关闭浏览器后重新打开,主题设置仍然保留</li>
<li>点击"重置为默认"会清除localStorage中的设置</li>
</ul>
</div>
</div>
);
}
function MultiTabSyncDemo() {
const [count, setCount] = useLocalStorage('sync-count', 0);
return (
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px', marginTop: '20px' }}>
<h3>跨标签页计数器同步</h3>
<p>当前计数: <strong>{count}</strong></p>
<p>尝试在多个标签页中打开这个页面,计数会自动同步</p>
<div style={{ display: 'flex', gap: '10px', marginTop: '20px' }}>
<button
onClick={() => setCount(prev => prev + 1)}
style={{
padding: '10px 20px',
background: '#28a745',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
增加
</button>
<button
onClick={() => setCount(prev => prev - 1)}
style={{
padding: '10px 20px',
background: '#dc3545',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
减少
</button>
<button
onClick={() => setCount(0)}
style={{
padding: '10px 20px',
background: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
重置
</button>
</div>
</div>
);
}
7.3 封装防抖Hook
// useDebounce.js
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
const timeoutRef = useRef(null);
useEffect(() => {
// 清除之前的定时器
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// 设置新的定时器
timeoutRef.current = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// 清理函数
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [value, delay]);
return debouncedValue;
}
// 使用示例
function SearchWithDebounce() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [isSearching, setIsSearching] = useState(false);
// 使用防抖Hook
const debouncedQuery = useDebounce(query, 500);
// 当防抖后的查询词变化时执行搜索
useEffect(() => {
const search = async () => {
if (!debouncedQuery.trim()) {
setResults([]);
return;
}
setIsSearching(true);
try {
// 模拟API调用
await new Promise(resolve => setTimeout(resolve, 800));
// 模拟搜索结果
const mockResults = Array.from({ length: 5 }, (_, i) => ({
id: i + 1,
title: `${debouncedQuery} 结果 ${i + 1}`,
description: `这是关于 ${debouncedQuery} 的第 ${i + 1} 个搜索结果`,
relevance: Math.random()
})).sort((a, b) => b.relevance - a.relevance);
setResults(mockResults);
} catch (error) {
console.error('搜索失败:', error);
setResults([]);
} finally {
setIsSearching(false);
}
};
search();
}, [debouncedQuery]);
return (
<div style={{ maxWidth: '600px', margin: '0 auto' }}>
<h3>防抖搜索示例</h3>
<p>输入搜索词,观察防抖效果(500ms延迟)</p>
<div style={{ marginBottom: '20px' }}>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="输入搜索词..."
style={{
width: '100%',
padding: '10px',
fontSize: '16px',
border: '1px solid #ddd',
borderRadius: '4px'
}}
/>
<div style={{ marginTop: '8px', fontSize: '14px', color: '#666' }}>
<p>实时输入: {query}</p>
<p>防抖后查询: {debouncedQuery}</p>
<p>防抖时间: 500ms</p>
</div>
</div>
{isSearching ? (
<div style={{ textAlign: 'center', padding: '40px' }}>
<div style={{
display: 'inline-block',
width: '40px',
height: '40px',
border: '4px solid #f3f3f3',
borderTop: '4px solid #3498db',
borderRadius: '50%',
animation: 'spin 1s linear infinite'
}} />
<p>搜索中...</p>
</div>
) : results.length > 0 ? (
<div>
<h4>搜索结果 ({results.length})</h4>
<ul style={{ listStyle: 'none', padding: 0 }}>
{results.map(result => (
<li
key={result.id}
style={{
padding: '15px',
marginBottom: '10px',
background: '#f8f9fa',
border: '1px solid #e9ecef',
borderRadius: '4px'
}}
>
<h5 style={{ margin: '0 0 8px 0' }}>{result.title}</h5>
<p style={{ margin: 0, color: '#666' }}>{result.description}</p>
<div style={{
marginTop: '8px',
fontSize: '12px',
color: '#888'
}}>
相关度: {(result.relevance * 100).toFixed(1)}%
</div>
</li>
))}
</ul>
</div>
) : debouncedQuery ? (
<div style={{ textAlign: 'center', padding: '40px', color: '#666' }}>
没有找到关于 "{debouncedQuery}" 的结果
</div>
) : (
<div style={{ textAlign: 'center', padding: '40px', color: '#666' }}>
输入搜索词开始搜索
</div>
)}
</div>
);
}
自定义Hook的设计原则:
- 以use开头:遵循React Hook的命名约定
- 封装通用逻辑:将可复用的状态逻辑提取到自定义Hook中
- 返回需要的值和方法:提供清晰的API接口
- 处理边界情况:考虑错误处理、清理函数等
- 保持Hook的纯粹性:避免在Hook中直接产生副作用
- 使用TypeScript:为自定义Hook提供类型定义,提高开发体验
在实际项目中,合理使用自定义Hook可以大幅提高代码的复用性和可维护性。我经常将表单处理、数据获取、本地存储等通用逻辑封装成自定义Hook,这样不仅减少了重复代码,也使得业务组件更加简洁清晰。
335



被折叠的 条评论
为什么被折叠?



