使用函数初始化商店时如何在 redux 工具包中获取 AppDispatch Typescript 类型?

How to get the AppDispatch Typescript type in redux toolkit when store is initialized with a function?

今天我的AppDispatch类型是从store.dispatch中提取的:

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import auth from "./auth/authSlice";
const rootReducer = combineReducers({ auth });
const store = configureStore({
  reducer: rootReducer
});
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export default store;

现在我尝试用 initStore 函数替换 store。我想使用 preloadedState 为我的商店补水。

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import auth from "./auth/authSlice";
const rootReducer = combineReducers({ auth });
const store = (preloadedState={}) => {
  return configureStore({
    reducer: rootReducer,
    preloadedState,
  });
}
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export default store;

我有一个错误:

Property 'dispatch' does not exist on type '(preloadedState?: {}) => EnhancedStore<CombinedState<{ auth: AuthState; }>, AnyAction, [ThunkMiddleware<CombinedState<{ auth: AuthState; }>, AnyAction, null> | ThunkMiddleware<...>]>'.ts(2339)

如何正确获取 AppDispatch 类型?

您已将 store 从实际的 Redux 存储实例更改为 "a function that returns a Redux store",但没有修复其余代码以匹配它。因此,第一个问题是 typeof store.dispatch; 在代码中的那一点不起作用,因为 store 是一个函数而不是实际的商店实例。

除此之外,我不确定您实际上是如何在这里获得 dispatch 的类型的,因为在定义类型时您还没有创建商店。我想你可以尝试这样的事情,但我不知道它是否有效:

const initStore = (preloadedState={}) => {
  return configureStore({
    reducer: rootReducer,
    preloadedState,
  });
}
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = ReturnType<typeof initStore>["dispatch"];
export default initStore ;