react-router-config 使用

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;
    原文作者:Y_qwq
    原文地址: https://segmentfault.com/a/1190000020084779
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞