首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Redux状态在具有两个存储区的mapStateToProps中未定义

Redux状态在具有两个存储区的mapStateToProps中未定义
EN

Stack Overflow用户
提问于 2019-06-04 17:10:53
回答 1查看 1.1K关注 0票数 14

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

代码语言:javascript
复制
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的配置

代码语言:javascript
复制
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交互的“助手”方法

代码语言:javascript
复制
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 dev-tools中,我可以看到存储在那里,被初始化并具有默认的初始状态。此外,我在存储上执行的调度(来自mapDispatchToProps)也在那里,并相应地更新存储。但在每个单独的mapStateToProps中,状态始终是undefined

大多数使用commonStore的组件实际上“活”在Ui.Common中,因为它们在Ui.WebApp中工作,而不是在Ui.Management中工作,所以问题很可能不在Ui.Common项目中。

这两个部分缩减器肯定设置了default,否则它将无法在这两个应用程序中的任何一个中工作。

EN

回答 1

Stack Overflow用户

发布于 2019-08-07 07:39:52

考虑创建一个可扩展的存储,以便将通用存储与自定义存储聚合在一起。尝试实现一个以自定义缩减程序为参数的函数,并将它们与commons聚合在一起。我尝试了一个类似的解决方案,它只需实例化一个rect-redux Provider即可轻松工作。类似于:

代码语言:javascript
复制
const createMyStore = (customReducers) => createStore(
  combineReducers({
    common: commonReducer,
    ...customReducers
  });
);

告诉我这个解决方案是否适合你。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56440840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档