【发布时间】:2019-02-15 05:32:09
【问题描述】:
我正在尝试将硬编码的<Route />s 块转换为从配置变量动态生成的东西。例如。
来自
<Router>
<Switch>
<Route path="/" component={Home} exact />
<Route path="/about" component={About} />
<Route path="/documents" component={Documents} exact />
<Route path="/documents/faq" component={DocFAQ} />
<Route path="/documents/translations" component={Translations} />
</Switch>
</Router>
到
const routes = [
{
path: '/',
component: Home,
exact: true
},
{
path: '/about',
component: About
},
{
path: '/documents',
component: Documents,
children: [
{
path: '/faq',
component: DocFAQ
},
{
path: '/translations',
component: Translations
}
]
}
];
const RecursiveRoute = ({ route, parentPath = '' }) => {
const path = parentPath + route.path;
return (
<React.Fragment>
<Route path={path} exact={route.exact || (route.children != null)} component={route.component} />
{route.children && route.children.map((childRoute, i) => <RecursiveRoute key={i} route={childRoute} parentPath={path} />)}
</React.Fragment>
);
};
const Routes = () => (
<Router>
<Switch>
{routes.map((route, i) => <RecursiveRoute key={i} route={route} />)}
</Switch>
</Router>
);
当我在<Router> 之外进行映射调用时,此代码会生成我想要的内容;例如。我可以验证它输出的代码与之前的硬编码块完全相同。然而,当它在<Switch> 内时,只有routes 数组中的第一条路由被映射——不会生成其他任何东西。将日志语句放入 <RecursiveRoute> 可以确认这一点。
为什么会这样,我该如何解决?
另一个奇怪的事情是,如果我将 <RecursiveRoute> 的 JSX 直接粘贴到 map 语句中,它会起作用(除非在这种情况下我不能使其递归):
<Switch>
{routes.map((route, i) => <Route key={i} path={route.path} exact={route.exact || (route.children != null)} component={route.component} />)}
</Switch>
但是如果我把它外包给另一个组件,映射又会失败。
[编辑]解决方案:
基于mehamasum's answer,将<RecursiveRoute>从组件改为函数解决了这个问题:
function generateRecursiveRoute(route, parentPath = '') {
const path = parentPath + route.path;
const routeHasChildren = (route.children != null);
const baseHtml = <Route path={path} exact={route.exact || routeHasChildren} component={route.component} key={path} />;
return !routeHasChildren ?
baseHtml :
<React.Fragment key={path}>
{baseHtml}
{route.children.map((childRoute) => generateRecursiveRoute(childRoute, path))}
</React.Fragment>;
}
const Routes = () => (
<Router>
<Switch>
{routes.map((route) => generateRecursiveRoute(route))}
</Switch>
</Router>
);
【问题讨论】:
-
“映射失败”是什么意思?抛出了某种错误?
-
就像“只有路由数组中的第一条路由被映射——没有其他的生成”。所以在这个例子中,只生成了 Home 路由。
标签: react-redux react-router react-router-v4