gpt4 book ai didi

reactjs - Webpack 5 模块联合微前端和 react-redux 不工作

转载 作者:行者123 更新时间:2023-12-05 04:49:07 30 4
gpt4 key购买 nike

尝试将现有的 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) 上运行良好

最佳答案

解决方案

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

// 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
]

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

自定义上下文的解决方案

如果您的应用有自定义上下文,则有类似的解决方案。看看 example在 module-federation-examples monorepo 中。

说明

Such errors arise when you have two copies of React Context in your apps . Redux、React Router、Material UI 和其他库在其提供程序中使用 Context API。因此,例如,当您在两个 WP5 联合模块中导入 Redux 时,每个模块(或应用程序)都有自己的 Redux 副本,即使它是相同版本。

解决方法

如果由于某种原因你不能拥有单例模块,有一个解决方法:将你的 Redux store 传递给远程应用程序的 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

关于reactjs - Webpack 5 模块联合微前端和 react-redux 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67716656/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com