React Router:将所有路由作为数组获取

IT技术 javascript reactjs react-router
2021-04-29 11:50:02

是否有一个现有的库可以将我的路由实例减少为一组路径?

示例

    <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 函数并解决这个问题,但我想知道是否有一个现有的库可以为我做这件事并处理使用 react 路由器表示路由的不同方式。

3个回答

由于我没有找到任何东西,我最终为此创建了一个库......

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']

我不明白你为什么需要一个图书馆。Routes应该Array在props中可用

一个例子:

在此处输入图片说明

我最近专门为此发布了一个库: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>