我确实有一个 React Redux 存储,它包装在 next-redux-wrapper 中。我想在 React 组件之外调度一个函数,但由于包装器的原因我无法这样做。有没有办法在使用包装器时导入存储并使用调度。以下片段:
export const rootReducer = combineReducers({...multiple_reducers_here});
const sagaMiddleware = createSagaMiddleware();
const makeConfiguredStore = () => {
const store = configureStore({
reducer: rootReducer,
middleware: [sagaMiddleware],
devTools: true,
});
sagaMiddleware.run(rootSaga);
return store;
};
export const makeStore = () => {
const persistConfig = {
key: 'nextjs',
whitelist: ['auth'],
storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store: any = configureStore({
reducer: persistedReducer,
middleware: [sagaMiddleware],
devTools: process.env.NODE_ENV !== 'production',
});
sagaMiddleware.run(rootSaga);
store.__persistor = persistStore(store); // Nasty hack
return store;
}
export const wrapper = createWrapper<AppStore>(makeStore);
export type AppStore = ReturnType<typeof makeStore>;
export type AppState = ReturnType<AppStore['getState']>;
我相信您应该能够正常创建商店并修改
makeStore
函数以简单地返回商店。
示例:
export const rootReducer = combineReducers({ ...multiple_reducers_here });
const sagaMiddleware = createSagaMiddleware();
const persistConfig = {
key: 'nextjs',
whitelist: ['auth'],
storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store: any = configureStore({
reducer: persistedReducer,
middleware: getDefaultMiddleware => getDefaulrMiddleware().concat(sagaMiddleware),
devTools: process.env.NODE_ENV !== 'production',
});
export const persistor = persistStore(store);
sagaMiddleware.run(rootSaga);
export const makeStore = () => store;
export const wrapper = createWrapper<AppStore>(makeStore);
export type AppStore = ReturnType<typeof makeStore>;
export type AppState = ReturnType<store.getState>;
您现在应该能够在代码中导入导出的
store
并调用 store.dispatch
将操作分派到为您的应用代码提供的同一商店实例。