一、 react-router vs react-router-dom
Note:?This package provides the core routing functionality for React Router, but you might not want to install it directly. If you are writing an application that will run in the browser, you should instead install?react-router-dom. Similarly, if you are writing a React Native application, you should instead install?react-router-native. Both of those will install?react-router?as a dependency.
官方文檔:https://reacttraining.com/react-router/web/guides/philosophy
二翅楼、快速上手
1.命令行依次輸入
項(xiàng)目構(gòu)建
npm install -g create-react-app
create-react-app demo-app
cd demo-app
安裝react-router-dom
npm install react-router-dom
2.入口文件路由配置(index.js)
import React from 'react';
import ReactDOM from "react-dom";
import { HashRouter as Router, Route, Link, Switch} from 'react-router-dom'
//這里使用引入的App組件
import App from './App';
ReactDOM.render(
????????( <HashRouter>
????????????????<Route path='/' component={App}/>
????????????????</HashRouter>
????????), document.getElementById('root')
);
3.App組件中定義路由
import React from'react';
import ReactDOM from"react-dom";
import { HashRouter as Router, Route,Link,Switch} from 'react-router-dom'
class App extends Component{
????????render() {
????????????????return(
? ? ? ? ????????????????<header>這是頭部公共部分</header>
? ? ? ? ????????????????<div>
????????????????????????????????{/*路由配置*/}
? ? ? ????????????????? </div>
? ? ? ? ? ? ? ?);
????????}
}
export default App;
4.總結(jié)
① 核心思想:router 是一個(gè)組件容器摔竿,可以裝一部分公共部分,可以在剩下需要切換的部分直接進(jìn)行路由配置灾挨。
② Switch:當(dāng)某一路由同時(shí)符合多個(gè)路由規(guī)則會(huì)帶來麻煩邑退,當(dāng)我們需要一個(gè)路由只為一匹配一個(gè)路由規(guī)則時(shí),需要switch劳澄,switch匹配到一個(gè)后不再繼續(xù)匹配后面的瓜饥,精準(zhǔn)匹配需要給route添加exact屬性。
三浴骂、路由傳值
1.params傳值
路由配置
<Route path='/detail/:id' component={Detail}/>
跳轉(zhuǎn)頁面
<Link to={'/detail/2'} >XXXX</Link>
//或者
this.props.history.push("/detail/2")
獲取頁面
this.props.match.params.id
//注意:有可能一個(gè)組件的子組件無法通過上面的代碼獲取到id可以使用withRouter(ChildName)來形成高階組件
import { withRouter} from 'react-router-dom';
export default withRouter(ChildName);
上面講的是傳一個(gè)值乓土,當(dāng)然也可以傳多個(gè)值
<Route exact path="/rgb/:r/:g/:b" component={RGB} />
this.props.match.params.r
this.props.match.params.g
this.props.match.params.b
2.query傳值
注意:路由配置不需要修改,傳遞一個(gè)對(duì)象,對(duì)象屬性包含pathname 和 query 趣苏,query屬性的值是要傳遞的對(duì)象狡相。
跳轉(zhuǎn)頁面
<Link to={{ pathname: '/detail',query:{type:'sex'}}}>XXXX</Link>
//或者
this.props.history.push({pathname:'/detail',query:{type:'sex'}})
獲取頁面參數(shù)
this.props.location.query.sex//建議不用 刷新頁面時(shí) 丟失
3.state傳值--秘密傳遞
注意:同query相似,state傳的參數(shù)不可見食磕,query傳的參數(shù)在地址欄可見尽棕;
跳轉(zhuǎn)頁面
<Link to={{ pathname: '/detail',state:{type:'sex'}}}>XXXX</Link>
//或者
this.props.history.push({pathname:'/detail',state:{type:'sex'}})
獲取頁面
this.props.location.state.sex//建議不用 刷新頁面時(shí) 丟失
四、路由跳轉(zhuǎn)
1.Link
<Link to="/detail/10003">詳情</Link>
2.Push
this.props.history.push("/")