咱們要的是一個簡單的react-router路由

咱們要的是一個簡單的react-router路由vue

習慣了 vue-router 路由的用法,再用react-router總感受挺麻煩的。react

那麼react有沒有用法跟vue-router同樣使用簡單的路由插件呢?git

管它有沒有,輪子我已經造好了,請收下react-concise-routergithub

react-concise-router

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> ) } } 複製代碼

API

new Router(options) 建立路由對象,返回router。

  • options object 路由配置的對象
  • options.mode string 定義路由類型,hash|history
  • options.routes array 路由列表
  • options.routes[].name string 路由名稱,若是當前存在children屬性,表示路由出口名稱
  • options.routes[].path string 路徑
  • options.routes[].component Function 路由組件;若是當前存在children屬性,表示子路由組件
  • options.routes[].children array 子路由列表

options.path 不存在或者爲 * 路由會當作notMath路由,匹配404

router

  • router.route(route) 生成url,用於history.push。

  • router.beforeEach(cxt, next) 路由切換中間件

router.view

<router.view /> 是一個路由出口組件。

props

  • props.name string 路由出口子名稱,默認'default';在 options.routes[].name 設置。

router.link

router.link 是一個相似於 Link 的組件。

props

  • props.to object|string 路徑或者路徑對象route。

router.beforeEach

router.beforeEach 是一個路由中間件,你能夠作一些路由切換事件;好比受權攔截,重定向,等待等操做。

你應該把它定義爲一個函數

router.beforeEach = function (ctx, next) {}
複製代碼
  • ctx 這個是一個上下文對象,{route, router, history,...}
  • next 這是一個回調函數,請在最後調用它;next 能夠接受一個字符串路徑或者對象,這樣能夠重定向到別的路由。

route

  • route.name string 命名路由name,優先於path
  • route.path string 路徑
  • route.params object 路由參數對象
  • route.query object 查詢字符串對象
  • route.hash string 連接hash

最後

安利一個詳細的列子:ant-admin-platform

源碼:react-concise-router

再說下:插件開發出來不久,可能存在一些問題,若是有問題,請提issues,感謝你的使用。 剛從事react開發不久,有什麼不合理的能夠在下方評論交流下。

相關文章
相關標籤/搜索