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