我想知道React Router是否有某种方法可以通过路由配置获取所有可能路径的列表?
例如,从此:
var routes = (
<Route name="/">
<DefaultRoute .../>
<Route name="about" .../>
<Route name="blog" .../>
</Route>
);
我想要:
["/", "/about", "/blog"]
我想知道React Router是否有某种方法可以通过路由配置获取所有可能路径的列表?
例如,从此:
var routes = (
<Route name="/">
<DefaultRoute .../>
<Route name="about" .../>
<Route name="blog" .../>
</Route>
);
我想要:
["/", "/about", "/blog"]
有几种方法可以做到这一点:
最简单的:通过检查您的道具 ( this.props.routes
) 将您的路线视为一个数组。但是,这包括许多您不一定要寻找的额外数据。
更健壮:使用社区构建的工具,如react-router-query、react-router-to-array或react-router-sitemap。都有相当强大的自述文件,您可以深入研究。
有人在此线程上提出了类似的问题,并给出了更详细的答复。
这似乎对我有用,v0.13:
var router = Router.create(routes);
var routePaths = [];
for (var i in router.namedRoutes) {
routePaths.push(router.namedRoutes[i].path);
}
//routePaths = ['/', '/about', '/blog']
为此,我编写了一个函数:
/**
* Get list of paths
* @param routes {JSX.Element}
*/
const getRoutes = (routes) =>
{
const paths = new Set();
/**
* Walk in list of routes tree
* @param element {JSX.Element}
*/
const walkTree = (element) =>
{
if (element.props.children && element.props.children.length > 0)
{
element.props.children.forEach((elem) => walkTree(elem));
}
else if (element.props.path && typeof element.props.path === 'string')
{
paths.add(element.props.path);
}
}
walkTree(routes);
return paths;
};
一个完整的反应样本(用反应 6 测试):
import './App.scss';
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Login from './pages/login.page';
import Pricing from './pages/pricing.page';
import Register from './pages/register.page';
import Home from './pages/home.page';
import Dashboard from './pages/dashboard.page';
import Authenticator from './components/Authenticator.component';
import Profile from './pages/Profile.page';
const App = () => {
const routes = (
<Routes>
<Route exact path='/login' element={<Login />} />
<Route exact path='/register' element={<Register />} />
<Route exact path='/pricing' element={<Pricing />} />
<Route path='/' element={<Authenticator />}/>
<Route exact path='/dashboard' element={<Dashboard />} />
<Route exact path='/profile' element={<Profile />} />
</Route>
<Route path='/*' element={<Home />} />
</Routes>
);
/**
* Get list of paths
* @param routes {JSX.Element}
*/
const getRoutes = (routes) =>
{
const paths = new Set();
/**
* Walk in list of routes tree
* @param element {JSX.Element}
*/
const walkTree = (element) =>
{
if (element.props.children && element.props.children.length > 0)
{
element.props.children.forEach((elem) => walkTree(elem));
}
else if (element.props.path && typeof element.props.path === 'string')
{
paths.add(element.props.path);
}
}
walkTree(routes);
return paths;
};
console.log(getRoutes(routes));
return (
<div className="App">
<main id='main' className="main">
{ routes }
</main>
</div>
);
}
export default App;