用来配置静态路由
Github https://github.com/remix-run/react-router
Star 44.3K
npm i react-router-config
// using an ES6 transpiler, like babel
import { matchRoutes, renderRoutes } from "react-router-config";
https://www.jianshu.com/p/f1a3184ac81c
https://www.jianshu.com/p/5ef6f8493c74
matchRoutes
import { matchRoutes } from 'react-router-config';
const routes =
function App({location}) {
const currentRoute = matchRoutes(routes, location.pathname)
}
静态路由
router.js
const routes = [
{ path: "/", exact: true, component: Home },
{
path: "/login",
component: Login,
requiresAuth: false,
},
{
path: "/user",
component: User,
requiresAuth: true, //需要登陆后才能跳转的页面
},
{
path: "*",
component: NotFound,
},
];
app.js
import { renderRoutes } from "react-router-config";
import routes from "./router.js";
const App = () => (
<main>
<Switch>{renderRoutes(routes)}</Switch>
</main>
);
export default App;
renderRoutes路由鉴权
renderRoutes 把routes做了个map,类似vue的 router.beforeEach路由守卫
如果 route.requiresAuth = false,或
- authed = true 或
- route.path === authPath(参数默认值’/login’),就渲染页面
- 否则就渲染我们设置的authPath页面,并记录从哪个页面跳转 ```jsx import React from “react”; import { Route, Redirect, Switch } from “react-router-dom”;
function renderRoutes(props) { const { routes, authed, authPath = “/login”, extraProps = {}, switchProps = {}, } = props;
if (!routes) return null;
return (
<Switch {...switchProps}>
{routes.map((route, i) => (
<Route
key={route.key || i}
path={route.path}
exact={route.exact}
strict={route.strict}
render={(props) => {
if (!route.requiresAuth || authed || route.path === authPath) {
return (
<route.component {...props} {...extraProps} route={route} />
);
}
return (
<Redirect
to={{ pathname: authPath, state: { from: props.location } }}
/>
);
}}
/>
))}
</Switch>
);
}
export default renderRoutes;
关键的鉴权代码
```jsx
if (!route.requiresAuth || authed || route.path === authPath) {
return <route.component {...props} {...extraProps} route={route} />;
}
return (
<Redirect to={{ pathname: authPath, state: { from: props.location } }} />
);
login
// 登陆之后返回原先要去的页面login函数
function Login({location, history}) {
const { state: from } = location || { state: { pathname: "/" } };
function onSubmit() {
// authed = true
history.push(from.pathname);
}
}