-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add useProState hook #2520
base: v4
Are you sure you want to change the base?
Conversation
* refactor: replace lodash/isEqual with react-fast-compare * chore: update lock --------- Co-authored-by: 云泥 <[email protected]>
* refactor(useLockFn): catch to finally * refactor(useLockFn): keep the throw e
…seExteneral` hook (alibaba#2508) * fix(type): fixed up some types that are non-standard and errors on `useExternal` hook * style: format * refactor: simplify --------- Co-authored-by: liuyib <[email protected]>
这个往 v4 分支合 |
|
都可以了,分支从 |
目前的getState还是不能实时获取到期待的setState之后的值,见这个issues,#2631 import { useState, type Dispatch, type SetStateAction, useCallback, useRef } from 'react';
import { isFunction } from 'ahooks/es/utils';
export type SetMergeState<S extends Record<string, never>> = <K extends keyof S>(
state: Pick<S, K> | null | ((prevState: Readonly<S>) => Pick<S, K> | S | null),
) => void;
export type DispatchType<S> = Dispatch<SetStateAction<S>>;
function useProState<S extends Record<string, never>>(
initialState?: S | (() => S),
): [
S,
{
setState: DispatchType<S>;
getState: () => S;
resetState: () => void;
setMergeState: SetMergeState<S>;
},
];
function useProState<S>(initialState?: S | (() => S)): [
S,
{
setState: DispatchType<S>;
getState: () => S;
resetState: () => void;
setMergeState: (s: Record<string, never>) => void;
},
];
function useProState<S>(initialState: S) {
const [state, setStatePrivate] = useState<S>(initialState);
const currentStateRef = useRef(state);
const setState = useCallback((patch: unknown) => {
const newState = isFunction(patch) ? patch(state) : patch;
setStatePrivate(newState);
currentStateRef.current = newState;
}, [state]);
const getState = useCallback(() => currentStateRef.current, []);
const resetState = useCallback(() => {
setState(initialState);
}, []);
const setMergeState = useCallback((patch: unknown) => {
const newState = isFunction(patch) ? patch(state) : patch;
const result = newState ? { ...state, ...newState } : state;
setStatePrivate(result);
currentStateRef.current = result;
}, [state]);
return [state, { setState, getState, resetState, setMergeState }];
}
export default useProState; |
可以考虑一下, @coding-ice 你看看呢,获取最新值的问题 |
[中文版模板 / Chinese template]
🤔 This is a ...
🔗 Related issue link
close: #2432
💡 Background and solution
📝 Changelog
☑️ Self Check before Merge