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

在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的用法,此后再發現有什么遺漏我會再繼續補充。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,533評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,055評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,365評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,561評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,346評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,889評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,978評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,118評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,637評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,558評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,739評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,246評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,980評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,619評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,347評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,702評論 2 370

推薦閱讀更多精彩內容