乐趣区

reactrouterconfig-使用

react-router-config

Static route config helpers
github: react-router-config

使用

需要注意的是,在 page2 中,renderRoutes(routes) 的 routes 是在 props 中获取的,即应该写成 renderRoutes(props.routes)

import React from "react";
import {renderRoutes} from "react-router-config";
import {HashRouter, Redirect} from "react-router-dom";

const routes = [{ path: "/", exact: true, render: () => <Redirect to={"/page1"} /> },
  {path: "/page1", component: Page1},
  {
    path: "/page2",
    component: Page2,
    routes: [
      {
        path: "/page2/child",
        component: Child
      }
    ]
  }
];

function App() {
  return (
    <HashRouter>
      <div className="App">
        <h1>Hello</h1>
        {renderRoutes(routes)}
      </div>
    </HashRouter>
  );
}

renderRoutes 源码

其实就是把你的 routes 做了个 map。
根据源码,就很容易做个类似 vue 的路由守卫了。思路可以参考利用 react-router4 的 react-router-config 做路由鉴权 – 个人文章 – SegmentFault 思否

import React from "react";
import {Switch, Route} from "react-router";

function renderRoutes(routes, extraProps = {}, switchProps = {}) {
  return routes ? (<Switch {...switchProps}>
      {routes.map((route, i) => (
        <Route
          key={route.key || i}
          path={route.path}
          exact={route.exact}
          strict={route.strict}
          render={props =>
            route.render ? (route.render({ ...props, ...extraProps, route: route})
            ) : (<route.component {...props} {...extraProps} route={route} />
            )
          }
        />
      ))}
    </Switch>
  ) : null;
}

export default renderRoutes;
退出移动版