简体   繁体   中英

Error: useRoutes() may be used only in the context of a <Router> component

I'm adding React modules dynamically using System JS, and it works great!
Except if I try to use the react-router context from the loaded module.

"react-router-dom": "6.0.0-beta.0"

You can see in the react component explorer that there is definitely a <Router> component as an ancestor.
The routing works fine in the host application - it only breaks when called from a dynamically loaded component.

I'm a novice with React, so I could be making a wrong assumption of how the contexts are provided to deeply nested or dynamically loaded children.

在此处输入图片说明

Router is mounted here -
https://github.com/savantly-net/sprout-platform/blob/47cb99f7076bf6df09d9fec8e2d6c7ee78ce08af/frontend/apps/webapp/src/index.tsx#L204

Module is being loaded here -
https://github.com/savantly-net/sprout-platform/blob/47cb99f7076bf6df09d9fec8e2d6c7ee78ce08af/frontend/apps/webapp/src/features/plugins/AppRootPage.tsx#L84

The module element that throws the exception is here -
https://github.com/savantly-net/sprout-platform/blob/47cb99f7076bf6df09d9fec8e2d6c7ee78ce08af/backend/modules/forms/src/plugin/FormsRootPage.tsx#L47

The problem was due to having the react-router-dom lib in the module bundle.
When the dynamic module loaded, it was using it's own version of the lib, rather then the one provided by the host application.

I added this to the externals in my webpack/rollup config, and the problem was solved.

I can now have children routes managed by a plugin inside a host application! =].

Webpack -
https://github.com/savantly-net/sprout-platform/blob/e746085ebd65820fd449c968385913f2cc86ee0d/frontend/tools/sprout-toolkit/src/config/webpack.plugin.config.ts#L176

Wrapping <App /> inside <Router> </Router> will resolve the issue.

import { BrowserRouter as Router } from "react-router-dom";

<Router>
 <App/>
</Router>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM