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

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

使用React構(gòu)建的單頁面應(yīng)用,要想實(shí)現(xiàn)頁面間的跳轉(zhuǎn),首先想到的就是使用路由。在React中,常用的有兩個(gè)包可以實(shí)現(xiàn)這個(gè)需求,那就是react-router和react-router-dom。本文主要針對react-router-dom進(jìn)行說明。

安裝

首先進(jìn)入項(xiàng)目目錄,使用npm安裝react-router-dom:

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

基本操作

然后我們新建兩個(gè)頁面,分別命名為“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

然后再新建一個(gè)路由組件,命名為“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;

如上代碼定義了一個(gè)純路由組件,將兩個(gè)頁面組件Home和Detail使用Route組件包裹,外面套用Switch作路由匹配,當(dāng)路由組件檢測到地址欄與Route的path匹配時(shí),就會(huì)自動(dòng)加載響應(yīng)的頁面。
然后在入口文件中——我這里指定的是index.js——編寫如下代碼:

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

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

這里相當(dāng)于向頁面返回了一個(gè)路由組件。我們先運(yùn)行項(xiàng)目看一下效果,在地址欄輸入“http://localhost:3000/#/”:

home.js

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

detail.js

通過a標(biāo)簽跳轉(zhuǎn)

可以看到其實(shí)路由已經(jīng)開始工作了,接下來我們再來做頁面間的跳轉(zhuǎn)。在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
重新打包運(yùn)行,在瀏覽器地址欄輸入“http://localhost:3000/”,試試看頁面能否正常跳轉(zhuǎn)。如果不能,請按步驟一步一步檢查代碼是否有誤。以上是使用a標(biāo)簽的href進(jìn)行頁面間跳轉(zhuǎn),此外react-router-dom還提供了通過函數(shù)的方式跳轉(zhuǎn)頁面。

通過函數(shù)跳轉(zhuǎn)

首先我們需要修改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')}>通過函數(shù)跳轉(zhuǎn)</button>
            </div>
        )
    }
}

在a標(biāo)簽下面添加一個(gè)按鈕并加上onClick事件,通過this.props.history.push這個(gè)函數(shù)跳轉(zhuǎn)到detail頁面。在路由組件中加入的代碼就是將history這個(gè)對象注冊到組件的props中去,然后就可以在子組件中通過props調(diào)用history的push方法跳轉(zhuǎn)頁面。

很多場景下,我們還需要在頁面跳轉(zhuǎn)的同時(shí)傳遞參數(shù),在react-router-dom中,同樣提供了兩種方式進(jìn)行傳參。

url傳參

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

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

然后修改detail.js,使用this.props.match.params獲取url傳過來的參數(shù):

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

在地址欄輸入“http://localhost:3000/#/detail/3”,打開控制臺:

可以看到傳過去的id=3已經(jīng)被獲取到了。react-router-dom就是通過“/:”去匹配url傳遞的參數(shù)。

隱式傳參

此外還可以通過push函數(shù)隱式傳參。

修改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
                        }
                })}>通過函數(shù)跳轉(zhuǎn)</button>
            </div>
        )
    }
}

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

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

跳轉(zhuǎn)后打開控制臺可以看到參數(shù)被打?。?/p>

其他函數(shù)

replace

有些場景下,重復(fù)使用push或a標(biāo)簽跳轉(zhuǎn)會(huì)產(chǎn)生死循環(huán),為了避免這種情況出現(xiàn),react-router-dom提供了replace。在可能會(huì)出現(xiàn)死循環(huán)的地方使用replace來跳轉(zhuǎn):

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

goBack

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

this.props.history.goBack();

嵌套路由

嵌套路由的適用場景還是比較多的,接下來就來介紹一下實(shí)現(xiàn)方法。
首先在Vue中實(shí)現(xiàn)嵌套路由,只需要將配置文件寫成children嵌套,然后在需要展示子路由的位置加上<router-view></router-view>即可。React中應(yīng)該如何實(shí)現(xiàn)呢?其實(shí)原理和Vue類似,只需要在父級路由中包含子路由即可。這樣說可能很多同學(xué)會(huì)一頭霧水,直接上代碼(不使用上面的例子):
首先定義父級組件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;

然后將它們添加進(jìn)路由router.js,并且關(guān)聯(lián)父子關(guān)系:

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>
        );
    }
}

如此,一個(gè)嵌套路由就完成了。

總結(jié)

這篇文章基本上涵蓋了大部分react-router-dom的用法,此后再發(fā)現(xiàn)有什么遺漏我會(huì)再繼續(xù)補(bǔ)充。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,979評論 25 709
  • 1. 11年出差去過美國的,當(dāng)時(shí)在底特律轉(zhuǎn)機(jī)到休斯頓參加OTC—石油展。 十幾個(gè)小時(shí)的飛機(jī)旅程早已經(jīng)把最開始的激動(dòng)...
    親哥拜閱讀 599評論 0 1
  • 夢里出現(xiàn)一個(gè)小小的匣子,淡黃色的外殼,開口被封死,輕輕搖晃沒有一點(diǎn)聲音。 我將它扔在床頭一隅,不去管它,它卻總是出...
    半目翅閱讀 679評論 0 0

友情鏈接更多精彩內(nèi)容