[inulax] 状态管理器dispatch方法异步使用时数据无法更新

This commit is contained in:
huangxuan 2023-11-30 16:13:51 +08:00
parent 3019fa5581
commit 0f87229318
No known key found for this signature in database
GPG Key ID: E79F50C67022565D
1 changed files with 14 additions and 16 deletions

View File

@ -41,29 +41,27 @@ export function createStoreHook(context: Context): () => ReduxStoreHandler {
}; };
} }
export function createSelectorHook(context: Context): (selector?: (any) => any) => any { export function createSelectorHook(context: Context): (selector?: ((state: unknown) => any) | undefined) => any {
const store = createStoreHook(context)() as unknown as ReduxStoreHandler; const store = createStoreHook(context)();
return function (selector = state => state) { return function useSelector(selector = state => state) {
const [b, fr] = useState(false); const [state, setState] = useState(() => store.getState());
useEffect(() => { useEffect(() => {
const unsubscribe = store.subscribe(() => fr(!b)); const unsubscribe = store.subscribe(() => {
return () => { setState(store.getState());
unsubscribe();
};
}); });
return () => unsubscribe();
}, []);
return selector(store.getState()); return selector(state);
}; };
} }
export function createDispatchHook(context: Context): () => BoundActionCreator { export function createDispatchHook(context: Context): () => BoundActionCreator {
const store = createStoreHook(context)() as unknown as ReduxStoreHandler; const store = createStoreHook(context)();
return function () { return function useDispatch() {
return action => { return store.dispatch;
store.dispatch(action);
}; };
}.bind(store);
} }
export const useSelector = selector => { export const useSelector = selector => {