react-router v5: react-router-config 配置型路由表

发布于 12/12/2019·评论 6

这几天一直在研究React应用,与React搭配的就是react-router,而且还支持了与VueRouter相同的集中型配置型路由表。其配置步骤如下:

1. 安装依赖

npm install react-router react-router-dom react-router-config

2. 根目录下新建一个router文件夹

router

router.js

import React from 'react'
import {
  Home,Books,Electronics,Mobile,Desktop,Laptop
} from '../pages/pages.js'
import Root from '../App.js'

const routes = [
  {
    component: Root,
    routes: [
      {
        path: '/',
        label: '首页',
        exact: true,
        component: Home
      },
      {
        path: '/books',
        label: '书籍',
        component: Books
      },
      {
        path: '/elec',
        label: '商城',
        component: Electronics,
        routes: [
          {
            path: '/elec/mobile',
            label: '移动',
            component: Mobile
          },
          {
            path: '/elec/desktop',
            label: '桌面',
            component: Desktop
          },
          {
            path: '/elec/laptop',
            label: '笔记本',
            component: Laptop
          }
        ]
      }
    ]
  }
]

export default routes

路由表的内容大概就是这个样子啦
把App.js作为路由的主出口, 其他的path,exact属性同react-router的属性。label属性是为了配置面包屑。如果子组件下还有子组件就用routes数组包含起来。

3. 在index.js文件中使用路由

src

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import routes from './router/router.js'
import { renderRoutes } from 'react-router-config'

ReactDOM.render(<Router>
  {renderRoutes(routes)}
  </Router>, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

把路由挂载到App下, 现在整个app就有了router对象了

4. 在组件中的应用

在组件的使用很简单,App组件中会在声明的路由中传递一个route参数,route是一个对象, 以上面的配置的路由表为例:

//home.jsx
import { renderRoutes } from 'react-router-config'
function Home ({ route }) {
  return (<> 
    {renderRoutes(route.routes)}
  </>)
}

route对象形如:
image

就这样哪一个组件有子组件了, 就在哪一个页面下配置一下。

参考链接

react-router-config 官方例子
react-router-config 搭建一个面包屑组件
react-router-config 的鉴权思想

更新时间:
stack-wuh 2020-05-08 02:14:06 更新
所属项目:
stack-wuh/blog
开源许可:
本文内容遵循 CC BY-NC-SA 4.0 协议,转载请注明文章出处与原文链接。
所属标签:
React

空空如也~

评论功能正在开发中,欢迎稍后回来留言交流。

logo
驿寄梅花, 鱼传尺素
Copyright©2024 Shadow.
你也想起舞吗
由next.js、mongodb和nest.js强力驱动
鄂ICP备20001814号-1
粤公网安备44030002001803号
等待播放
PLAYER
加载默认歌单...
等待播放
等待播放
00:0000:00
音量
歌词
暂无歌词
播放列表