是否存在将路由实例减少到路径数组的现有库?
示例:
<Route path="/" component={App}>
<Route path="author" component={Author}>
<Route path="about" component={About}/>
</Route>
<Route path="users" component={Users} />
</Route>
输出
['/', '/author', '/author/about', '/users']
我可以写一个reduce函数,它只有很少的代码行并解决了这个问题,但我想知道是否有一个现有的库可以为我做这件事,并负责使用反应路由器表示路由的不同方法。
答案 0 :(得分:12)
由于我没有找到任何东西,我最终为此创建了一个库...
https://github.com/alansouzati/react-router-to-array
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import reactRouterToArray from 'react-router-to-array';
// or var reactRouterToArray = require('react-router-to-array');
console.log(reactRouterToArray(
<Route path="/" component={FakeComponent}>
{/* just to test comments */}
<IndexRoute component={FakeComponent} />
<Route path="about" component={FakeComponent}>
<Route path="home" component={FakeComponent} />
<Route path="/home/:userId" component={FakeComponent} />
</Route>
<Route path="users" component={FakeComponent} />
<Route path="*" component={FakeComponent} />
</Route>)
); //outputs: ['/', '/about', '/about/home', '/users']
答案 1 :(得分:3)
答案 2 :(得分:0)
我最近发布了专门用于此目的的库:https://github.com/elliottsj/react-router-query
它可以处理异步路由(即getChildRoutes
/ getIndexRoute
),并且不仅提供路径数组,还提供一个&#34; FlatRoute&#34;包含路径(fullPath
)的对象,以及每个路由的所有原始属性,以及一个&#34; parent&#34;路线:
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 },
],
},
]);
});
请注意,只有&#34; leaf&#34;路由包含在结果中:没有&#34; FlatRoute&#34; 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>
如果您想要/posts
的FlatRoute,只需添加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>