react初見路由

第一種傳有限參數

首先創建路由,在創建路由之前要安裝關於路由的插件,下這個命令

npm install react-router-dom --save-dev
//安裝完以後就會在package.json中看到這個代碼,代表安裝成功
"devDependencies": {
    "react-router-dom": "^5.0.0"
  }
  1. 創建/router/index.js文件,代碼如下
/*
 HashRouter:有#號
 BrowserRouter:沒有#號
 Switch:只要匹配到一個地址不往下匹配,相當於for循環裏面的break
 Link:跳轉頁面,相當於vue裏面的router-link
 exact :完全匹配路由
* */

import React, {Fragment} from 'react';
import {HashRouter as Router, Route, Switch} from 'react-router-dom';
import App from "../App";
import NewsIndex from "../pages/news/index";
import NewsDetail from "../pages/news/details";

export default class RouterComponent extends React.Component {
    render() {
        return (
            //下面的代碼固定模式
            <Fragment>
                <Router>
                    <Fragment>
                        <Switch>
                            {/*導入App組件  exact指的是完全匹配 /  這是路由*/}
                            <Route exact path="/" component={App}/>
                            {/* path是 調用路由路徑   NewsIndex是我創建的組件,新聞列表*/}
                            <Route path="/news/index" component={NewsIndex}/>
                            {/* /:id 傳參數id     /:title傳參數標題  這個有一個侷限性,定義完路由後只能傳固定的參數*/}
                            <Route path="/news/details/:id/:title" component={NewsDetail}/>
                        </Switch>
                    </Fragment>
                </Router>
            </Fragment>
        )
    }
}
  1. 在src下的index.js裏面改變入口,改成路由組件
// 原來的默認代碼 ReactDOM.render(<App/>, document.getElementById('root'));
ReactDOM.render(<RouterComponent/>, document.getElementById('root'));
  1. <App/>組件中加入一個按鈕
<button onClick={this.toNewsIndex.bind(this,'/news/index')}>點擊跳轉新聞界面</button>
//跳轉新聞列表界面的方法
    toNewsIndex(path) {
        this.props.history.push(path)
}
  1. 新聞列表界面
import React from 'react';
import {HashRouter as Router, Route, Switch, Link} from 'react-router-dom';

export default class NewsIndex extends React.Component {
    render() {
        return (
            <div>
                <div>我是新聞界面</div>
                <ul>
               		 {/*Link是跳轉頁面標籤  /1/新聞頭條一 是傳的id和title參數 */}
                    <li><Link to='/news/details/1/新聞頭條一'>新聞頭條一</Link></li>
                    <li><Link to='/news/details/2/新聞頭條二'>新聞頭條二</Link></li>
                </ul>
            </div>
        )
    }
	 //跳轉新聞詳情界面
    toNewsDetailThree(path){
        this.props.history.push(path)
    }
}
  1. 新聞詳情界面
import React from 'react';

export default class detailsIndex extends React.Component {
    componentWillMount() {
        //打印出路徑和參數
        console.log(this.props);
    }
    render() {
        //獲取參數
        let id = this.props.match.params.id;
        let title = this.props.match.params.title;
        return (
            <div>
                我是新聞詳情頁,id爲{id},標題爲{title}
            </div>
        )
    }
}

第二種可以傳無限參數用法可以結合上面的代碼來看
1、設置路由

 <Route path="/news/details" component={NewsDetail}/>

2、新聞列表頁點擊跳轉條目可以這樣寫

 <li onClick={this.toNewsDetailThree.bind(this,'/news/details?id=3&title=新聞頭條三')}>新聞頭條三</li>

3、新聞詳情頁獲取參數

		//獲取參數
        let id = localParam(this.props.location.search).search.id;
        //由於中文傳過去亂碼,所以用decodeURIComponent解析,localParam是用來解析 ?id=3&title=新聞頭條三   這串
        let title = decodeURIComponent(localParam(this.props.location.search).search.title);

4、解析?id=3&title=新聞頭條三 用到的方法

function localParam (search, hash) {
    search = search || window.location.search;
    hash = hash || window.location.hash;
    var fn = function(str, reg) {
        if (str) {
            var data = {};
            str.replace(reg, function($0, $1, $2, $3) {
                data[$1] = $3;
            });
            return data;
        }
    }
    return {
        search : fn(search, new RegExp("([^?=&]+)(=([^&]*))?", "g")) || {},
        hash : fn(hash, new RegExp("([^#=&]+)(=([^&]*))?", "g")) || {}
    }
}
export {
    localParam
}

不記入記錄的跳轉,比如A->B->C,如果B->C跳轉採用的是this.props.history.replace(path),那麼C點返回鍵回到的是A

//用法類似this.props.history.push(path),
this.props.history.replace(path)

返回上一個頁面的方法

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