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


 

安裝

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

基本操作

我們新建兩個頁面,分別命名為‘home’和‘mine’。這頁面中編寫如下代碼:

 import React from 'react';
 //home.js
 export default class Home extends React.Component {
     render() {
         return (
             <div>
                 <a>去mine</a>
             </div>
         )
     }
 }
 //mine.js
import React from 'react';
 
 export default class Mine extends React.Component {
     render() {
         return (
             <div>
                 <a>回到home</a>
           </div>
        )
     }
 }

然后再新建一個路由組件,命名為‘Router.js’,並編寫如下代碼:

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


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


export default BasicRoute;

如上代碼定義了一個純路由組件,將兩個頁面組件Home和Mine使用Router組件包裹,外面套用Swicth做路由匹配,當路由組件檢測到地址欄與Router的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/#/”:

 

 

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

 

 通過a標簽跳轉

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

//home.js
import React from 'react';

export default class Home extends React.Component {
   render() {
      return (
            <div>
                <a href='#/mine'>去mine</a>
            </div>
        )
    }
}
//mine.js
import React from 'react';


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

重新打包運行,在瀏覽器地址欄輸入“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這個函數跳轉都mine頁面,在路由組件中加入的代碼就是將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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM