首页 > 解决方案 > 在具有两个存储的 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集合,否则它在这两个应用程序中的任何一个中都不起作用。

标签: typescriptreduxreact-redux

解决方案


考虑创建一个可扩展的存储来聚合通用存储和自定义存储。尝试实现一个将自定义减速器作为参数并将它们与公共资源聚合的函数。我尝试了一个类似的解决方案,它可以轻松地仅实例化一个rect-redux Provider. 就像是:

const createMyStore = (customReducers) => createStore(
  combineReducers({
    common: commonReducer,
    ...customReducers
  });
);

告诉我该解决方案是否适合您。


推荐阅读