在React中使用react-router-dom路由

1,路由組件的基本實現react

  使用React構建的單頁面應用,要想實現頁面間的跳轉,首先想到的就是使用路由。在React中,經常使用的有兩個包能夠實現這個需求,那就是react-router和react-router-dom。本文主要針對react-router-dom進行說明。npm

  安裝:瀏覽器

    首先進入項目目錄,使用 npm 安裝 react-router-domreact-router

$ npm i react-router-dom -S

  基本操做:dom

     而後咱們新建兩個頁面,分別命名爲「home」和「detail」。在頁面中編寫以下代碼:函數

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a>去detail</a>
            </div>
        )
    }
}

    home.jsthis

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a>回到home</a>
            </div>
        )
    }
}

    detail.jsurl

       而後再新建一個路由組件,命名爲「Router.js」,並編寫以下代碼:spa

import React from 'react';
import {HashRouter, Route, Switch} from 'react-router-dom';
import Home from '../home';
import Detail from '../detail';


const BasicRoute = () => (
    <HashRouter>
        <Switch>
            <Route exact path="/" component={Home}/>
            <Route exact path="/detail" component={Detail}/>
        </Switch>
    </HashRouter>
);


export default BasicRoute;

    如上代碼定義了一個純路由組件,將兩個頁面組件Home和Detail使用Route組件包裹,外面套用Switch做路由匹配,當路由組件檢測到地址欄與Route的path匹配時,就會自動加載響應的頁面。
    而後在入口文件中——我這裏指定的是index.js——編寫以下代碼:code

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router/router';

ReactDOM.render(
  <Router/>,
  document.getElementById('root')
);

2,路由跳轉

  1) 經過 a 標籤

   能夠看到其實路由已經開始工做了,接下來咱們再來作頁面間的跳轉。在home.js和detail.js中,咱們修改以下代碼:

import React from 'react';


    export default class Home extends React.Component {
        render() {
            return (
                <div>
                <a href='#/detail'>去detail</a>
            </div>
        )
    }
}

  home.js

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a href='#/'>回到home</a>
            </div>
        )
    }
}

  detail.js
  從新打包運行,在瀏覽器地址欄輸入「http://localhost:3000/」,試試看頁面可否正常跳轉。若是不能,請按步驟一步一步檢查代碼是否有誤。以上是使用a標籤的href進行頁面間跳轉,此外react-router-dom還提供了經過函數的方式跳轉頁面。

  2) 經過函數跳轉

  首先咱們須要修改router.js中的兩處代碼:

import React from 'react'
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom'

<HashRouter history>
      <Switch>
            <Route exact path="/" component={Home}/>
            <Route path="/Detail" component={Detail}/>
            <Route path="/Find" component={Find}/>
            <Route path="/Save" component={Save}/>
        </Switch>
</HashRouter>

  而後在home.js中:
  import React from 'react';

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    
    render() {
        return (
            <div>
                <a href='#/detail'>去detail</a>
                <button onClick={() => this.props.history.push('detail')}>經過函數跳轉</button>
            </div>
        )
    }
}

  在a標籤下面添加一個按鈕並加上onClick事件,經過this.props.history.push這個函數跳轉到detail頁面。在路由組件中加入的代碼就是將history這個對象註冊到組件的props中去,而後就能夠在子組件中經過props調用history的push方法跳轉頁面。

  不少場景下,咱們還須要在頁面跳轉的同時傳遞參數,在react-router-dom中,一樣提供了兩種方式進行傳參。

3,路由傳參

  1) URl 傳參

     在router.js中,修改以下代碼:

<Route exact path="/detail/:id" component={Detail}/>

   而後修改detail.js,使用this.props.match.params獲取url傳過來的參數:

componentDidMount() {
    console.log(this.props.match.params);
}

  2) 隱式 傳參

     此外還能夠經過push函數隱式傳參。

      修改home.js代碼以下:

import React from 'react';


export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    
    render() {
        return (
            <div>
                <a href='#/detail/3'>去detail</a>
                    <button onClick={() => this.props.history.push({
                        pathname: '/detail',
                        state: {
                            id: 3
                        }
                })}>經過函數跳轉</button>
            </div>
        )
    }
}

  在detail.js中,就可使用this.props.history.location.state獲取home傳過來的參數:

componentDidMount() {
    console.log(this.props.history.location.state);
}

4,其餘函數

  1) replace

     有些場景下,重複使用push或a標籤跳轉會產生死循環,爲了不這種狀況出現,react-router-dom提供了replace。在可能會出現死循環的地方使用replace來跳轉:

this.props.history.replace('/detail');

  2) goBack

     場景中須要返回上級頁面的時候使用:

this.props.history.goBack();
相關文章
相關標籤/搜索