- 背景:开发过程经常遇到需求选中某条记录,然后点击提交的时候由于useState是异步实现,导致拿不到最新的值。
- 实现:参照ahook的useGetState改造,用useState和useRef结合实现了新的useGetState,使用方式跟useState类似,返回值里面加多一个实时更新的值getState
- 代码:源码如下(复制粘贴即可使用):
import type { Dispatch, SetStateAction } from 'react'
import { useState, useRef, useCallback } from 'react'
type GetStateAction<S> = () => S
function useGetState<S>(
initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>, GetStateAction<S>]
function useGetState<S = undefined>(): [
S | undefined,
Dispatch<SetStateAction<S | undefined>>,
GetStateAction<S | undefined>
]
function useGetState<S>(initialState?: S) {
const [state, setState] = useState(initialState)
const stateRef = useRef(state)
stateRef.current = state
const setCurrentState = (pre: SetStateAction<S | undefined | any>) => {
setState(pre)
if (typeof pre === 'function') {
stateRef.current = pre(state)
} else {
stateRef.current = pre
}
}
const getState = useCallback(() => stateRef.current, [])
return [state, setCurrentState, getState]
}
export default useGetState