首页 > 解决方案 > 使用函数初始化商店时如何在redux工具包中获取AppDispatch Typescript类型?

问题描述

今天我的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 类型?

标签: typescriptreduxredux-toolkit

解决方案


您已经store从实际的 Redux 存储实例更改为“返回 Redux 存储的函数”,而没有修复其余代码以匹配它。所以,第一个问题是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 ;

推荐阅读