首页 文章

结合2个不同项目的2个redux商店

提问于
浏览
2

首先,我是React&Redux的初学者 .

我正在尝试将组件从一个项目转移到另一个项目 . 我把一个项目作为npm包,所以我可以直接从这个项目导入 . 问题是我在我的主项目中使用了一个商店,而我的npm包也使用了商店 . 这导致状态未定义,因为我只给一个商店提供商 .

这是我的主项目的index.js,我知道你不能有2个提供商,但我想指出我正在寻找两个商店的功能:

import { guiReducer, intlInitialState } from 'second-project';
const secondStore = createStore(guiReducer, intlInitialState);
const store = configureStore();

render(
<Provider store={store}>
 <Provider store={secondStore}
  <Router>
   <App />
  </Router>
 </Provider>
</Provider>

这是configureStore.js:

import rootReducer from '../reducers';

function configureStoreProd(initialState){
 return createStore(
  rootReducer,
  initialState,
  applyMiddleware(thunk)
  );
}

const configureStore =
  process.env.NODE_ENV === 'production' ? configureStoreProd : configureStoreDev;


export default configureStore;

rootReducer是主项目的组合减速器,guiReducer是第二个项目的组合减速器 . rootReducer的示例代码(类似于guiReducer):

const appReducer = combineReducers({
 loggedIn,
 courses,
 lessons,
 organisation,
});

const rootReducer = (state,action) => {
 if (action.type === LOGOUT) {
   state = initialState;
 }
 return appReducer(state,action);
};

export default rootReducer;

我还试图结合root / gui-reducers并创建一个像这样的新商店(configureStore.js):

function configureCombinedStoreProd(initialState){
 return createStore(
   combineReducers({
    rootReducer,
    guiReducer,
   }), initialState, applyMiddleware(thunk)
 );
}

const configureCombinedStore = 
 process.env.NODE_ENV === 'production' ? configureCombinedStoreProd : 
   configureCombinedStoreDev; 

export {configureCombinedStore as configureCombinedStore };

提前致谢 .

2 回答

  • 0

    我目前通过在第二个项目中使用 <Provider store={store}> 包装App.js中的组件来解决这个问题,而在index.js "App"中包含来自主项目的提供程序 . 不确定这是否是最佳做法 .

  • 0

    我"reducers"文件夹中的减速器 . 相反,如果你使用“duck pattern”,你可能也想在npm包中保存旧的reducer(只有减压器,而不是商店!),并在你的新店里调用 combineReducers 之类的东西时将它们导入你的商店.js文件 .

相关问题