useLatest
跟踪 React State 的最新值。
Usage
实时编辑器
function Demo() { const [count, setCount] = useState(0); const latestCount = useLatest(count); const handleAlertClick = () => { setTimeout(() => { alert(`最新的计数值: ${latestCount.current}`); }, 3000); }; return ( <div> <p>您点击了 {count} 次</p> <button onClick={() => setCount(count + 1)}>点击我</button> <button onClick={handleAlertClick}>显示警告</button> </div> ); };
结果
您点击了 0 次
API
useLatest
Returns
React.MutableRefObject<T>: ref 对象
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| value | 追踪值 | T (必填) | - |