学习react全家桶的时候肯定会使用react-router4.0

react-router和vue-router对比起来,感觉vue-router设计的真的是简单好用啊。

但是react可以通过一款react-router-config插件做到和vue-router一样的使用感

npm 仓库:https://www.npmjs.com/package/react-router-config

react-router-config的源码

import React from "react";
import Switch from "react-router/Switch";
import Route from "react-router/Route";
const renderRoutes = (routes, extraProps = {}, switchProps = {}) =>
routes ? (
    <Switch {...switchProps}>
        {routes.map((route, i) => ( 
        <Route
          key={route.key || i}
          path={route.path}
          exact={route.exact}
          strict={route.strict}
          render={props => (
            <route.component {...props} {...extraProps} route={route} />
          )}
        />
      ))}
    </Switch>
  ) : null;
 export default renderRoutes;

route.js

const routes = [
    { path: '/',
        exact: true,
        component: Home,
    },
    {
        path: '/login',
        component: Login,
    },
    {
        path: '/user',
        component: User,
    },
    {
        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

简单用法就是这样

扩展文章:

1.react-router配置鉴权:https://segmentfault.com/a/1190000015282620

Logo

前往低代码交流专区

更多推荐