用来配置静态路由
Github https://github.com/remix-run/react-router
Star 44.3K

  1. npm i react-router-config
  2. // using an ES6 transpiler, like babel
  3. import { matchRoutes, renderRoutes } from "react-router-config";

https://www.jianshu.com/p/f1a3184ac81c
https://www.jianshu.com/p/5ef6f8493c74

matchRoutes

  1. import { matchRoutes } from 'react-router-config';
  2. const routes =
  3. function App({location}) {
  4. const currentRoute = matchRoutes(routes, location.pathname)
  5. }

静态路由

router.js

  1. const routes = [
  2. { path: "/", exact: true, component: Home },
  3. {
  4. path: "/login",
  5. component: Login,
  6. requiresAuth: false,
  7. },
  8. {
  9. path: "/user",
  10. component: User,
  11. requiresAuth: true, //需要登陆后才能跳转的页面
  12. },
  13. {
  14. path: "*",
  15. component: NotFound,
  16. },
  17. ];

app.js

  1. import { renderRoutes } from "react-router-config";
  2. import routes from "./router.js";
  3. const App = () => (
  4. <main>
  5. <Switch>{renderRoutes(routes)}</Switch>
  6. </main>
  7. );
  8. 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;

  1. if (!routes) return null;
  2. return (
  3. <Switch {...switchProps}>
  4. {routes.map((route, i) => (
  5. <Route
  6. key={route.key || i}
  7. path={route.path}
  8. exact={route.exact}
  9. strict={route.strict}
  10. render={(props) => {
  11. if (!route.requiresAuth || authed || route.path === authPath) {
  12. return (
  13. <route.component {...props} {...extraProps} route={route} />
  14. );
  15. }
  16. return (
  17. <Redirect
  18. to={{ pathname: authPath, state: { from: props.location } }}
  19. />
  20. );
  21. }}
  22. />
  23. ))}
  24. </Switch>
  25. );

}

export default renderRoutes;

  1. 关键的鉴权代码
  2. ```jsx
  3. if (!route.requiresAuth || authed || route.path === authPath) {
  4. return <route.component {...props} {...extraProps} route={route} />;
  5. }
  6. return (
  7. <Redirect to={{ pathname: authPath, state: { from: props.location } }} />
  8. );

login

  1. // 登陆之后返回原先要去的页面login函数
  2. function Login({location, history}) {
  3. const { state: from } = location || { state: { pathname: "/" } };
  4. function onSubmit() {
  5. // authed = true
  6. history.push(from.pathname);
  7. }
  8. }