Nas*_*sto 13 typescript redux react-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')
);
Run Code Online (Sandbox Code Playgroud)
配置为 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;
}
Run Code Online (Sandbox Code Playgroud)
这些是我与进行交互的“帮助器”方法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);
}
Run Code Online (Sandbox Code Playgroud)
在其中一个应用程序(Ui.WebApp)中,它可以按预期工作,两个商店独立工作,一切都很好。
在第二个应用程序(Ui.Management)中,commonConnect它似乎无法正常工作。在redux dev-tools中,我可以看到商店在那里,被初始化并具有默认的初始状态。此外,mapDispatchToProps我在商店上执行的调度(来自)也在那里,并相应地更新了商店。但是在每一个mapStateToProps状态中总是如此undefined。
大多数组件消耗了commonStore实际的“活动”内容,Ui.Common而在其中工作Ui.WebApp而不是在其中工作时Ui.Management,问题很可能不在Ui.Common项目内。
肯定有两个部分化简的default集,否则它将无法在这两个应用程序中的任何一个中运行。
小智 1
考虑创建一个可扩展的商店来聚合通用商店和自定义商店。尝试实现一个将自定义减速器作为参数并将它们与公共项聚合的函数。我尝试了一种类似的解决方案,它可以轻松地仅实例化一个rect-redux Provider. 就像是:
const createMyStore = (customReducers) => createStore(
combineReducers({
common: commonReducer,
...customReducers
});
);
Run Code Online (Sandbox Code Playgroud)
告诉我该解决方案是否适合您。
| 归档时间: |
|
| 查看次数: |
253 次 |
| 最近记录: |