2

尝试将现有的 react + redux 应用程序迁移到微前端。

Container (Parent App) - localhost:8080
ReactReduxApp (Child App - 1) - localhost:8081
ReactApp (Child App - 2) - localhost:8082

独立应用程序可以在其 PORT 中使用 react-redux 运行。当作为容器应用程序内的子应用程序访问它时,容器应用程序没有加载并抛出错误

Error: Could not find "store" in the context of "Connect(IndexPage)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(IndexPage) in connect options.

没有ReactReduxApp(Child1)我的Container(Parent)应用程序在ReactApp(Child2)下运行良好

4

2 回答 2

1

解决方案

用于singleton: true每个使用 React Context 的共享库:

// webpack.config.js

// import package.json to get packages' versions
const deps = require('./package.json').dependencies

module.exports = {
  // ...
  plugins: [
    new ModuleFederationPlugin({
      name: 'main',
      filename: 'remoteEntry.js',
      remotes: {
        // your remotes config
      },
      shared: {
        react: {
          singleton: true,
          version: deps['react']
        },
        'react-dom': {
          singleton: true,
          version: deps['react-dom']
        },
        'react-router-dom': {
          singleton: true,
          version: deps['react-router-dom']
        },
        'react-redux': {
          singleton: true,
          version: deps['react-router-dom']
        }
      },
    }),
    // other plugins
  ]

在所有联合模块中使用此设置。

自定义上下文的解决方案

如果您的应用程序具有自定义上下文,则有类似的解决方案。查看module-federation-examples monorepo 中的示例

解释

当您的应用程序中有两个 React Context 副本时,就会出现此类错误。Redux、React Router、Material UI 和其他库在其提供程序中使用 Context API。因此,例如,当您在两个 WP5 联合模块中导入 Redux 时,每个模块(或应用程序)都有自己的 Redux 副本,即使它的版本相同。

解决方法

如果由于某种原因你不能有单例模块,有一个解决方法:将你的 Redux 存储传递给远程应用程序的 props 并用另一个 Provider 包装它,如下所示:

// in your remote app:
const RemoteAppWrapper = ({ store }) => {
  return (
    <Provider store={store}>
      <RemoteApp />
    </Provider>
  );
};

// and then in your host app:
<RemoteApp store={store} />

在官方 module-federation-examples monorepo 中有一个带有完整示例的应用程序,其中使用了这种方法:https ://github.com/module-federation/module-federation-examples/tree/master/redux-reducer-injection

于 2021-06-18T14:27:23.877 回答
-1

也许你应该试试这个redux-micro-frontend而不是 origin redux

于 2021-06-11T06:55:22.527 回答