reactjs - 组合来自 2 个不同项目的 2 个 redux 存储

标签 reactjs redux react-redux

首先,我是 React 和 Redux 的初学者。

我正在尝试将组件从一个项目获取到另一个项目。我将一个项目制作为 npm 包,这样我就可以直接从该项目导入。问题是我在我的主项目中使用了一个商店,并且我的 npm 包也使用了一个商店。这会导致状态未定义,因为我只向提供商提供一个商店。

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

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 是来自主项目的组合 reducer ,guiReducer 是来自第二个项目的组合 reducer 。 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 };

提前致谢。

最佳答案

我建议您避免在 npm 包中保存另一个商店。相反,只将您需要的组件包装在 npm 包中,让它们接受与“store”不同的属性,并将旧项目的 reducer 复制到“reducers”文件夹中。相反,如果您使用“duck pattern ”,您可能还想将旧的 reducer 保存在 npm 包中(仅保存 reducer ,而不是存储!),并在调用类似 combineReducers 之类的内容时将它们导入您的存储中。在新的 store.js 文件中。

关于reactjs - 组合来自 2 个不同项目的 2 个 redux 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49070201/

相关文章:

javascript - 登录 React-Redux 后无法重定向

javascript - 通过多个 Action 类型来约束 reducer

javascript - react 未捕获类型错误 : Cannot read property '__reactAutoBindMap' of undefined

javascript - 类型 '(event: FormEvent<HTMLInputElement>) => void' 不可分配给类型 '() => any'

json - Algolia是否有一种方法可以用逗号分隔的JSON字段创建单独的细化方面

reactjs - React Redux 组件不更新

javascript - 使用reactjs在tic tac toe应用程序中渲染图像

react-redux - 为什么调用 connect 函数时不使用 mapStateToProps 或 mapDispatchToProps 作为参数?

javascript - "Stateless function components cannot be given refs"是什么意思?

javascript - webpack 'import' 仅在顶层