【问题标题】:Redux state is undefined in mapStateToProps with two stores在具有两个存储的 mapStateToProps 中未定义 Redux 状态
【发布时间】:2019-06-04 09:10:53
【问题描述】:

我有两个 react 应用程序,每个应用程序都有自己的 redux 存储(在 ASP.Net Core 内,但我认为这无关紧要)。我发现两个应用程序之间有很多重复的代码,所以我为两个项目之间的共享代码创建了一个Ui.Common 项目。在那个范围内,我介绍了一个commonStore,这两个应用程序中的每一个都使用它以及它们自己的商店。 根据文档,我在它自己的 React-Context 上初始化了 commonStore,当需要 commonStore 时,connect 调用引用了相同的上下文。对于我所做的商店的初始化:

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 项目中。

这两个部分 reducer 肯定有他们的 default 设置,否则它不会在两个应用程序中的任何一个中工作。

【问题讨论】:

标签: typescript redux react-redux


【解决方案1】:

考虑创建一个可扩展的存储来聚合通用存储和自定义存储。尝试实现一个将自定义减速器作为参数并将它们与公共资源聚合的函数。 我尝试了一个类似的解决方案,它很容易只实例化一个rect-redux Provider。 比如:

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

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

【讨论】:

    猜你喜欢
    • 2016-12-22
    • 2020-11-15
    • 2016-09-19
    • 1970-01-01
    • 2019-01-15
    • 2017-06-13
    • 2019-09-20
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多