模块联盟 |无效的挂钩调用。钩子只能在函数组件体内调用

问题描述 投票:0回答:2

我正在尝试远程使用 React 组件,它只有简单的计数器应用程序(

useState
)。 以及使用 React 和 Redux 的 Host 应用程序。

远程作为一个独立的应用程序工作正常,但是当它被主机使用时出现以下错误

enter image description here

react-dom.production.min.js:209 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我尝试过的:

这是我的 webpack 配置

[

remote
]

 new ModuleFederationPlugin({
      name: 'RemoteMap',
      filename: 'Remote.js',

      exposes: {
        './Bootstrap': resolvePath(process.cwd(), 'src/common/components/organisms/remote/index.tsx')
      },
      shared: {

        "react": {
          eager: true,
          singleton: true,
          strictVersion: true,
          requiredVersion: dependencies.react
        },
        "react-redux": {
          eager: true,
          singleton: true
        },
        'react-dom': {
          eager: true,
          singleton: true
        }
      }
    })

[主持人]

 new ModuleFederationPlugin({
      name: 'Host',
      remotes: {
        // remote: ,
        myApp: 'RemoteMap@http://localhost:8081/Remote.js'
      }
    }),

上述错误的可能原因和解决方法是什么。 ?

reactjs react-hooks micro-frontend webpack-module-federation
2个回答
1
投票

我在使用 React 配置主机时遇到了同样的问题。为了解决这个问题,我将依赖项添加为共享:

const packageJson = require('./package.json');

...

new ModuleFederationPlugin({
    name: "App",
    remotes: {
      HomeApp: "HomeApp@http://localhost:9002/remoteEntry.js",
      ContactApp: "ContactApp@http://localhost:9003/remoteEntry.js",
      //HomeApp: lazyLoadRemote("http://localhost:9002/remoteEntry.js","HomeApp"),
      //ContactApp: lazyLoadRemote("http://localhost:9003/remoteEntry.js","ContactApp"),
    },
    shared: {...packageJson.devDependencies}
  }),

0
投票

对于最新的React,我们应该共享相同的react-dom/client

// host

new container.ModuleFederationPlugin({
  shared: {
    react: {
      eager: true,
      singleton: true,
      requiredVersion: deps.react,
    },
    'react-dom/client': {
      eager: true,
      singleton: true,
      requiredVersion: deps['react-dom'],
    },
  },
}),

// remote

new ModuleFederationPlugin({
  name: "react_mfe_app",
  exposes: {
    ReactAppLoader: "./src/loader.ts",
  },
  shared: {
    react: {
      singleton: true,
    },
    "react-dom/client": {
      singleton: true,
    },
  },
  filename: "remoteEntry.js",
}),

对于远程,如果我将

react-dom/client
更改为
react-dom
它将引发错误

© www.soinside.com 2019 - 2024. All rights reserved.