1. 程式人生 > 其它 >在React中使用react-router-dom路由

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

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

aimmarc 72018.05.07 13:06:16字數 1,174閱讀 248,738

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

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

安裝

首先進入專案目錄,使用npm安裝react-router-dom:

npm install react-router-dom --save-dev //這裡可以使用cnpm代替npm命令

基本操作

然後我們新建兩個頁面,分別命名為“home”和“detail”。在頁面中編寫如下程式碼:

import React from 'react';


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

home.js

import React from 'react';


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

detail.js

然後再新建一個路由元件,命名為“Router.js”,並編寫如下程式碼:

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——編寫如下程式碼:

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

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

這裡相當於向頁面返回了一個路由元件。我們先執行專案看一下效果,在位址列輸入“http://localhost:3000/#/”:

home.js

輸入“http://localhost:3000/#/detail”:

detail.js

通過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還提供了通過函式的方式跳轉頁面。

通過函式跳轉

首先我們需要修改router.js中的兩處程式碼:

...
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom';
...
<HashRouter history={hashHistory}>
...

然後在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中,同樣提供了兩種方式進行傳參。

url傳參

在router.js中,修改如下程式碼:

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

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

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

在位址列輸入“http://localhost:3000/#/detail/3”,開啟控制檯:

可以看到傳過去的id=3已經被獲取到了。react-router-dom就是通過“/:”去匹配url傳遞的引數。

隱式傳參

此外還可以通過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.match.params);
    console.log(this.props.history.location.state);
}

跳轉後開啟控制檯可以看到引數被列印:

其他函式

replace

有些場景下,重複使用push或a標籤跳轉會產生死迴圈,為了避免這種情況出現,react-router-dom提供了replace。在可能會出現死迴圈的地方使用replace來跳轉:

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

goBack

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

this.props.history.goBack();

巢狀路由

巢狀路由的適用場景還是比較多的,接下來就來介紹一下實現方法。
首先在Vue中實現巢狀路由,只需要將配置檔案寫成children巢狀,然後在需要展示子路由的位置加上<router-view></router-view>即可。React中應該如何實現呢?其實原理和Vue類似,只需要在父級路由中包含子路由即可。這樣說可能很多同學會一頭霧水,直接上程式碼(不使用上面的例子):
首先定義父級元件MainLayout

import React from 'react';
import './MainLayout.scss';

const { Header, Sider, Content } = Layout;


export default class MainLayout extends React.Component {

    render() {
        return (
            <div className='main-layout'>
                父元件
            </div>
        );
    }
}

然後定義子元件Home:

import React, {useState} from 'react';
import {Modal, Select} from "antd";
import {connect} from 'react-redux';
import {addCount} from '../../servers/home';


function Home(props) {
    const [visible, setVisible] = useState(false);
    const {countNum: {count}, dispatch} = props;

    return (
        <div>
            子元件
        </div>
    )
}

export default Home;

然後將它們新增進路由router.js,並且關聯父子關係:

import React from 'react';
import {HashRouter, Route, Switch} from "react-router-dom";
import Home from '../pages/Home/Home';
import MainLayout from '../layout/MainLayout';

const BasicRouter = () => (
    <HashRouter>
        <Switch>
            <Route path="/index" component={
                <MainLayout>
                  <Route exact path="/" component={Home}/>
                  <Route exact path="/index" component={Home}/>
                  <Route path="/index/home" component={Home}/>
                </MainLayout>
             }/>
        </Switch>
    </HashRouter>
);


export default BasicRouter;

在MainLayout中,修改如下程式碼:

import React from 'react';
import './MainLayout.scss';

const { Header, Sider, Content } = Layout;


export default class MainLayout extends React.Component {

    render() {
        return (
            <div className='main-layout'>
                {this.props.children}
            </div>
        );
    }
}

如此,一個巢狀路由就完成了。

總結

這篇文章基本上涵蓋了大部分react-router-dom的用法,此後再發現有什麼遺漏我會再繼續補充。

漫思