前言
给
https://ahooks.gitee.io/zh-CN/hooks/use-get-stateReact.useState
增加了一个 getter 方法,以获取当前最新值。
源码
https://github.com/alibaba/hooks/blob/master/packages/hooks/src/useGetState/index.ts
useGetState的基础用法,它比React.useState,返回值多了第三个参数,可以通过函数式的方式获取最新state值
const [count, setCount, getCount] = useGetState(0);
ahooks.useGetState
init是初始化的值,然后在set一个值后,可以看到在set后立即调用get函数,返回的仍然是init值
重写
跟 ahooks.useGetState 差别点在于 setState 的时候就给临时 ref 立即做一个存储,达到在设置后立马可以获取
import { useRef, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import type { Dispatch, SetStateAction } from 'react'
type GetStateAction<T> = () => T;
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<T>(initialData?: T): [(T | undefined), Dispatch<SetStateAction<T | undefined>>, GetStateAction<T | undefined>] {
const ref = useRef(initialData)
const [s, setS] = useState(initialData)
const getState = useMemoizedFn(() => ref.current)
// set 值的时候,直接赋值给 ref。且支持 React.useState 的语法
const setState = useMemoizedFn((patch: any) => {
ref.current = typeof patch === 'function' ? patch(getState()) : patch
setS(patch)
})
return [s, setState, getState]
}
export default useGetState
测试例子
源码 & demo
https://github.com/8696/react-app/blob/master/src/hooks/useGetState/index.ts