Redux +打字稿:如何实现'injectReducer'?

wyyhbhjk  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在开发一个使用redux来管理状态的typescript react应用程序。
为了动态添加约简器,redux建议实现一个injectReducer函数。
我已经在一个Javascript项目中完成了这一点,但是我不知道如何使用typescript完成这一点。
任何建议都会很有帮助!
到目前为止,我已经尝试过:

export interface AppStore extends EnhancedStore<{}> {
  injectedReducers?: any;
}

const store: AppStore = configureStore({
  reducer: createReducer(),
  devTools: process.env.NODE_ENV !== "production",
});

store.injectedReducers = {};

export const injectReducer = (key: string, reducer: Reducer<object>) => {
  if (store.injectedReducers[key]) {
    return;
  }
  store.injectedReducers[key] = reducer;

  store.replaceReducer(createReducer(store.injectedReducers));
  return store;
};

export default function createReducer(injectedReducers?: any) {
  return combineReducers({
    global: globalReducer,
    ...injectedReducers,
  });
}

下面是来自createReducer(store.injectedReducers!)的错误消息:

Argument of type 'Reducer<CombinedState<{ [x: string]: unknown; }>, never>' is not assignable to parameter of type 'Reducer<{}, AnyAction>'.
  Types of parameters 'action' and 'action' are incompatible.
    Type 'AnyAction' is not assignable to type 'never'.ts(2345)
b91juud3

b91juud31#

我使用的解决方法是从我的存储文件中导出另一个函数,该函数将向我的存储中注入reducer。

import selectedContextSlice from "./selectedContextSlice";
import { combineReducers, configureStore, Reducer } from "@reduxjs/toolkit";
import { userProfileSlice } from "./userProfileSlice";
import { viewSlice } from "./viewSlice";
import authClientsSlice from "./authClientsSlice";

const containerReducers = {
  authClients: authClientsSlice.reducer,
  selectedContext: selectedContextSlice.reducer,
  userProfile: userProfileSlice.reducer,
  view: viewSlice.reducer
};

const store = configureStore({ reducer: containerReducers });

function registerReducers(newReducers: Reducer) {
  store.replaceReducer(
    combineReducers({ ...containerReducers, ...newReducers })
  );
}

export default store;
export { registerReducers as injectReducers };
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

相关问题