useState取最新值和上次值方案
文章类型:React
发布者:hp
发布时间:2026-07-18
在 React 中,useState 返回的 state 值是异步更新的,你无法在调用 setState 后立即拿到最新值,因为状态更新是批量且异步的
使用 useRef 缓存最新值:useRef 的 .current 属性在渲染间保持不变,可同步保存最新状态。import React, { useState, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const countRef = useRef(count); // 用于同步保存最新值
const handleIncrement = () => {
setCount(prev => {
countRef.current = prev + 1; // 实时更新 ref
return prev + 1;
});
// 此时 count 仍是旧值,但 countRef.current 是最新值
console.log('最新值(通过 ref):', countRef.current); // ✅ 立即拿到最新值
};
return <button onClick={handleIncrement}>+1</button>;
}
使用 useRef + useEffect 组合记录上一次值:在每次 state 变化时,将当前值存入 ref,并在下次更新时读取上一次的值。
import React, { useState, useEffect, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count; // 每次更新后保存当前值为“上一次”
}, [count]);
const handleIncrement = () => {
setCount(c => c + 1);
};
return (
<div>
<p>当前值: {count}</p>
<p>上一次值: {prevCountRef.current}</p>
<button onClick={handleIncrement}>+1</button>
</div>
);
}
暂无评论,快来发表第一条评论吧~