咱們要的是一個簡單的react-router路由vue
習慣了 vue-router 路由的用法,再用react-router總感受挺麻煩的。react
那麼react有沒有用法跟vue-router同樣使用簡單的路由插件呢?git
管它有沒有,輪子我已經造好了,請收下react-concise-router。github
react-concise-router
是一個基於 react-router v4.x 封裝的一個路由插件。vue-router
有了這個插件,你能夠不用再去學 react-router v4.x
那些文檔了,直接用這個插件,就能夠實現你須要的路由。npm
直接安裝react-router
npm install -S react-concise-router
複製代碼
你還須要安裝dom
npm install -S react-router
複製代碼
npm install -S react-router-dom
複製代碼
router.js函數
import Router from 'react-concise-router'
import Home from './views/Home'
import User from './views/User'
import UserInfo from './views/UserInfo'
import ErrorPage from './views/Error'
import view from './views/admin/view'
import Dashboard from './views/admin/Dashboard'
const router = new Router ({
mode: 'hash',
routes: [
{path: '/', component: Home},
{path: '/user', component: User},
{path: '/user/:userId', name: 'info', component: UserInfo},
{
path: '/admin',
component: view,
name: 'admin-view',
children: [
{path: '/', component: Dashboard},
{path: '/test', component: Dashboard},
{component: ErrorPage}
]
},
{path: '*', component: ErrorPage},
]
})
export default router
複製代碼
App.jsxui
import React from 'react'
import router from './router'
export default class App extends React.Component {
render () {
return (
<div> <p>wellcome !</p> <router.view /> </div> ) } } 複製代碼
new Router(options) 建立路由對象,返回router。
options.path
不存在或者爲*
路由會當作notMath路由,匹配404
router.route(route) 生成url,用於history.push。
router.beforeEach(cxt, next) 路由切換中間件
<router.view />
是一個路由出口組件。
props
options.routes[].name
設置。router.link
是一個相似於 Link
的組件。
props
router.beforeEach
是一個路由中間件,你能夠作一些路由切換事件;好比受權攔截,重定向,等待等操做。
你應該把它定義爲一個函數
router.beforeEach = function (ctx, next) {}
複製代碼
next
能夠接受一個字符串路徑或者對象,這樣能夠重定向到別的路由。安利一個詳細的列子:ant-admin-platform
再說下:插件開發出來不久,可能存在一些問題,若是有問題,請提issues,感謝你的使用。 剛從事react開發不久,有什麼不合理的能夠在下方評論交流下。