使用react-router-dom路由實現頁面跳轉傳參

BrowserRouter和HashRouter路由模式

  • BrowserRouter
    • 如果前端使用了browserRouter,每次改變路由時,會向服務器發送請求,因爲服務器未配置對應的路徑指向對應的文件,自然導致出現404的情況.(對於初始化頁面,即路由爲/時,不會發送請求)
  • HashRouter
    • 由於hashRouter會在路徑上添加#分隔路徑,而#後面的所有請求都不會發送到服務器端,即對於服務器而言,路徑依舊是localhost:3000,路由切換在前端完成。

如果做服務端渲染的話建議使用BrowserRouter, 在開發階段可以在webpack devServer中配置historyApiFallback: true,或者在使用BrowserRouter需要再加一層服務器配置(node/nginx),讓前端發送的請求映射到對應的html文件上。不然還是建議用HashRouter。

HashRouter路由

  • 新建兩個js文件,分別命名爲“home”和“other”

home.js文件

import React from 'react';

export default class Home extends React.Component {

    constructor(props){
        super(props);
    }

    render() {
        return (
            <div>
                {/* 地址欄跳轉 */}
                {/* <a href='#/other/1'>跳轉到other頁面</a> */}

                <button onClick={ ()=>{
                    this.props.history.push({
                        pathname : '/other',
                        state :{
                            id:3
                        }
                    });

                    //在可能會出現死循環的地方使用replace來跳轉
                    // this.props.history.replace('/other');
                    // this.props.history.replace({
                    //     pathname:'/other',
                    //     state : {
                    //         id:4
                    //     }
                    // });

                    //返回上級頁面
                    // this.props.history.goBack();
                    }
            }> 使用函數跳轉到other頁面 </button>
            </div>
        )
    }
}

other.js文件

import React from 'react';

export default class Other extends React.Component {

    constructor(props){
        super(props);
    }
    
    componentDidMount(){
        //地址欄跳轉傳參
        // console.log(this.props.match.params);

        //函數跳轉傳參
        console.log(this.props.history.location.state);
    }

    render() {
        return (
            <div>
                <a href='#/'>回到home頁面</a>
            </div>
        )
    }
}
  • 新建一個HashRouter路由組件

Router.js文件

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

const BasicRoute = () => (
   <HashRouter>
       <Switch>
           <Route exact path="/" component={Home}/>
           <Route exact path="/other" component={Other}/>
           {/* 地址欄跳轉傳參 */}
           {/* <Route exact path="/other/:id" component={Other}/> */}
       </Switch>
   </HashRouter>
);

export default BasicRoute;

以上定義了一個HashRouter路由組件,將兩個頁面組件Home和Other使用Route組件包裹,外面套用Switch作路由匹配,當路由組件檢測到地址欄與Route的path匹配時,就會自動加載響應的頁面。

  • 在入口文件index.js中配置
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Router from './Router';

ReactDOM.render(
	<Router />,
	document.getElementById('root')
);
頁面跳轉:
  • a標籤跳轉:<a href='#/'>回到home</a>

  • 函數跳轉:

    • this.props.history.push('/other');
    • this.props.history.replace('/other');//避免重複使用push或a標籤跳轉產生死循環時使用
    • this.props.history.goBack('/other');//返回上級頁面
跳轉傳參:
  • url傳參
    • 路由組件配置<Route exact path="/other/:id" component={Other}/>跳轉時配置<a href='#/other/1'>跳轉到other頁面</a>,react-router-dom就是通過/:去匹配url傳遞的參數
  • 函數隱式傳參
    • 向跳轉函數添加參數(以push()函數爲例)
      	//push()與replace()、goBack()同理
         this.props.history.push({
             pathname : '/other',
             state :{
                   id:3
            }
        });
      
    查看參數集:
    • url傳參方式:this.props.match.params
    • 函數隱式傳參方式:this.props.history.location.state

BrowserRouter路由

  • 修改Router.js文件,成爲一個BrowserRouter路由組件

Router.js文件

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Home from './home';
import Other from './other';

const BasicRoute = () => (
   <HashRouter>
       <BrowserRouter>     
       <Route  exact  path="/"   component={Home}/>
       <Route  path="/other"  name="other" component={Other}/>
       </BrowserRouter>
   </HashRouter>
);

export default BasicRoute;
頁面跳轉:
  • a標籤跳轉:<Link exact to="/other">點擊跳轉</Link>注意: 引入import {Link} from 'react-router-dom';

  • 函數跳轉:與HashRouter路由方式相同

跳轉傳參:
  • url傳參

    • HTML方式:<Link to={{ pathname : ' /user' , state : { day: 'Friday' }}}>點擊跳轉</Link>注意: 引入import {Link} from 'react-router-dom';
  • 函數隱式傳參

    • 向跳轉函數添加參數與HashRouter路由方式相同

    查看參數集:

    • 函數隱式傳參方式:與HashRouter路由方式相同

歡迎訪問本文的個人博客鏈接: https://br-bai.github.io/2019/09/29/使用react-router-dom路由實現頁面跳轉傳參/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章