我最近专门为此发布了一个库:https : //github.com/elliottsj/react-router-query
它可以处理异步路由(即getChildRoutes
/ getIndexRoute
),不仅提供路径数组,还提供包含路径 ( fullPath
)的“FlatRoute”对象数组,以及每条路由的所有原始属性,以及“父级”数组” 路线:
import { query } from 'react-router-query';
const routes = (
<Route path="/" component={App}>
<Route path="author" component={Author}>
<Route path="about" component={About} />
</Route>
<Route path="users" component={Users} />
</Route>
);
query('/', routes, (error, result) => {
expect(result).toEqual([
{
fullPath: '/author/about'
component: About,
parents: [
{ path: '/', component: App },
{ path: 'author', component: Author },
],
},
{
fullPath: '/users'
component: Users,
parents: [
{ path: '/', component: App },
],
},
]);
});
请注意,只有“叶子”路线包括在结果:没有“FlatRoute”对象fullPath: '/'
,也没有fullPath: '/author'
。这是为了防止包含仅用作子路由布局的路由,例如
<Route path="/" component={App}>
<Route path="posts" component={PostLayout}>
<Route path="1" component={Post1} />
<Route path="2" component={Post2} />
<Route path="3" component={Post3} />
</Route>
</Route>
如果你想要一个 FlatRoute for /posts
,只需包含一个IndexRoute
:
<Route path="/" component={App}>
<Route path="posts">
<IndexRoute component={Posts} />
<Route path="1" component={Post1} />
<Route path="2" component={Post2} />
<Route path="3" component={Post3} />
</Route>
</Route>