typescript - 在具有两个存储的 mapStateToProps 中未定义 Redux 状态
问题描述
我有两个 react 应用程序,每个都有自己的 redux 商店(在 ASP.Net Core 内,但我认为这无关紧要)。我发现两个应用程序之间有很多重复的代码,所以我Ui.Common
为两个项目之间的共享代码创建了一个项目。在那个范围内,我介绍了commonStore
两个应用程序中的每一个都使用以及它们自己的商店。根据文档,我commonStore
在它自己的 React-Context 上初始化,并且在connect
需要时调用引用相同的上下文commonStore
。对于我做的商店的初始化:
const store = ReduxStore.configureStore(history);
const commonStore = CommonStore.configureStore();
ReactDOM.render(
<Provider store={store}>
<Provider store={commonStore} context={CommonContext}>
<ConnectedRouter history={history} children={routes} />
</Provider>
</Provider>,
document.getElementById('react-app')
);
配置为CommonStore
public configureStore() {
const windowIfDefined = typeof window === 'undefined' ? null : window as any;
// If devTools is installed, connect to it
const devToolsExtension = windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__ as () => StoreEnhancer;
const createStoreWithMiddleware = compose(devToolsExtension ? devToolsExtension() : <S>(next: StoreEnhancerStoreCreator<S>) => next)(createStore);
const store = createStoreWithMiddleware(rootReducer()) as Store<CommonAppState>;
return store;
}
这些是我与以下交互的“帮助”方法commonStore
:
export function rootReducer(): Reducer<CommonAppState> {
return combineReducers<CommonAppState>({
app: appReducer,
userSettings: userSettingsReducer
});
}
export const CommonContext = React.createContext<ReactReduxContextValue>(undefined);
/** A connect wrapper to connect specifically to the common redux store. */
export function commonConnect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?: ConnectOptions) {
if (!options) {
options = {};
}
options.context = CommonContext;
return connect(mapStateToProps, mapDispatchToProps, mergeProps, options);
}
在其中一个应用程序 ( Ui.WebApp
) 中,这按预期工作,两个商店独立工作,一切都很好。
在第二个应用程序 ( Ui.Management
) 中,commonConnect
似乎无法正常工作。在 redux 开发工具中,我可以看到商店在那里,被初始化并具有默认的初始状态。此外,我在商店执行的调度(来自mapDispatchToProps
)在那里并相应地更新商店。但是在每一个mapStateToProps
状态中总是undefined
。
大多数消耗commonStore
实际“实时”的组件,Ui.Common
并且当它们在其中工作Ui.WebApp
而不是在 中工作时Ui.Management
,问题很可能不在Ui.Common
项目中。
这两个部分减速器肯定有它们的default
集合,否则它在这两个应用程序中的任何一个中都不起作用。
解决方案
考虑创建一个可扩展的存储来聚合通用存储和自定义存储。尝试实现一个将自定义减速器作为参数并将它们与公共资源聚合的函数。我尝试了一个类似的解决方案,它可以轻松地仅实例化一个rect-redux Provider
. 就像是:
const createMyStore = (customReducers) => createStore(
combineReducers({
common: commonReducer,
...customReducers
});
);
告诉我该解决方案是否适合您。
推荐阅读
- c++ - UE4 关于附件规则的崩溃
- gitlab - 是否可以在 gitlab 中覆盖 $CI_PROJECT_NAME ?
- c# - 为什么 Regex.Replace 给我最后一组奇怪的结果
- laravel - 无法在网络上加载徽标
- regex - 将正则表达式搜索合并为一个匹配项
- django-rest-framework - 如何在 Django-REST 中使用 ListField 字段发出 PUT/PATCH 请求?
- r - RStudio --> 错误:找不到 Python 模块 tensorflow.keras
- excel - 本月的下一个第 n 天 - excel
- json - DJANGO REST - 基于类的视图 - POST、GET 请求不按定义工作
- angular - Angular e2e 量角器 browser.wait 不起作用