在Router中包含来自另一个包的路由集合



这里有一个快速的问题,我有下面的代码,我希望能够从我的包中导入很多路由。导入的路由应该由我正在构建的包控制。如果我在包中添加一个新页面(比如,ForgotPassword),那么我就不想来这里手动添加ForgotPassword条目了…当我更新到最新版本的软件包时,它应该就开始工作了。

另外,这个路由集合在我的包项目中会是什么样子?

欢迎有任何想法:D

...
import { RouteCollectionFromPackage } from "@my/package";
...
<Router basename="/">
<Suspense fallback={<div>Loading...</div>}>
<Switch>
{ /* I WANT TO IMPORT A COLLECTION OF ROUTES FROM MY PACKAGE */}
<RouteCollectionFromPackage />

{ /* THESE ARE IN MY APP */}
<Route exact path="/" component={home} />
<Route exact path="/search" component={search} />

</Switch>
</Suspense>
</Router>

谢谢! !

<标题>

编辑:这就是我所尝试的,在遵循了下面的一些建议之后:

In my module:

const Routes = [
<Route exact path="/Login" component={Login} />,
<Route exact path="/ForgotPassword" component={Login} />,
<Route exact path="/MyProfile" component={Login} />
];
export { Routes };

在我的消费应用中:

import { Suspense, lazy } from "react";
import { HashRouter as Router, Switch, Route } from "react-router-dom";
import { Routes as PortalFrameworkRoutes, Login} from "@sal/portal";
const home = lazy(() => import("./pages/home/Home"));
const search = lazy(() => import("./pages/search/Search"));

function routes() {
return (
<Router basename="/">
<Suspense fallback={<div>Loading...</div>}>
<Switch>
{PortalFrameworkRoutes.map((route: Route) => route)}
<Route exact path="/" component={home} />
<Route exact path="/search" component={search} />
</Switch>
</Suspense>
</Router>
);
}
export default routes;

我得到错误:

Error: Invariant failed: You should not use <Route> outside a <Router>

或者当我使用{...PortalFrameworkRoutes}时,我得到:

Spread children are not supported in React
<标题>

编辑# 2:这实际上可能是我遗漏的一个关键信息。在我的模块中,路由被导出,并在index.tsx中导入(并再次导出),如下所示:

export { Routes } from "./routes";
export { Login } from "./pages/login/Login";

我不确定这是否100%正确,但感觉正确,因为我只想从模块的顶层导入,并在那里提供一切。即import { Routes as PortalFrameworkRoutes, Login } from "@sal/portal";

在包中,像这样导出路由:

const yourRoutes = [
<Route ... />,
<Route ... />,
];
export { yourRoutes };

将其导入到您的消费应用程序中:

import { yourRoutes } from '@your/package';

然后使用数组展开操作符将它们包含在其他路径上:

<Switch>
{...yourRoutes}
<Route path="/some/application/route" component=... />
</Switch>

在你的@my/package"模块,你应该导出一个对象数组,其中每个对象都有一个路径和组件属性,然后你可以动态渲染

然后在当前文件中,您可以使用map方法来呈现它们


//"@my/package" module
//make sure to import the necessary components you will be adding 
import component1 from "//..."
import component2 from "//..."
.
import componentN from "//..."
export myRoutes = [
{path: "/pathToComponent1", component: component1}
{path: "/pathToComponent2", component: component2}
.
{path: "/pathToComponentN", component: componentN}
]

// in your current module
import {myRoutes} from "@my/package"
<Router>
<switch>
...  
// where you need to render routes from your module
{myRoutes.map(route => <Route path={route.path} component={route.component}/>}
...
</switch>
</Router>

最新更新