原理:通过同步更新 useRef 来获取最新值
1 2 3 4 5 6 7 8 9 10 11 |
// util.ts export const useRefState = (init: any = null) => { const [state, setState] = useState(init); const stateRef = useRef(init); const setProxy = (newVal: any) => { stateRef.current = newVal; setState(newVal); }; const getState = () => stateRef.current; return [state, setProxy, getState]; }; |
使用:
1 2 3 4 5 6 7 |
import { useRefState } from "util" const [state, setState, getState] = useRefState(0) state // state 值,变动后更新DOM setState // setState,变动 state getState() // 获取最新值 |