首頁  >  文章  >  web前端  >  react-router路由的簡單分析

react-router路由的簡單分析

不言
不言原創
2018-07-13 16:26:431941瀏覽

這篇文章主要介紹了關於react-router路由的簡單分析,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

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

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

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

那麼react有沒有用法跟vue-router一樣使用簡單的路由外掛呢?

管它有沒有,輪子我已經造好了,請收下。

react-concise-router

react-concise-router 是基於 react-router v4.x 封裝的一個路由外掛程式。

1、安裝

直接安裝

npm install -S react-concise-router

你還需要安裝

npm install -S react-router
npm install -S react-router-dom

2、定義路由清單物件

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.jsx

import React from 'react'
import router from './router'

export default class App extends React.Component {
  render () {
    return (
      <p>
        <p>wellcome !</p>
        <router.view />
      </p>
    )
  }
}

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路由,匹配404router

  • router.route(route)

    產生url,用於history.push。

  • router.beforeEach(cxt, next)

    路由切換中間件

  • 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

  • #以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

對於React 元件和state|props的解析


如何使用JS實作一個簡易數位時鐘

以上是react-router路由的簡單分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn