使用功能初始化商店时,如何在Redux工具包中获取AppDispatch Typescript类型?

时间:2020-05-23 17:46:12

标签: typescript redux redux-toolkit

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

1 个答案:

答案 0 :(得分:1)

您已将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 ;