此教程基于React Router 4.0
React-router和React-router-dom的選擇
很多剛使用react的同學在接觸到react-router的時候就會很蛋疼擎淤,什么react-router和react-router-dom淌铐?往往開始會比較懵逼。下面我們就來一探究竟相种。
React-router
React-router提供了一些router的核心api颅和,包括Router, Route, Switch等搓彻,但是它沒有提供dom操作進行跳轉(zhuǎn)的api空扎。
React-router-dom
React-router-dom提供了BrowserRouter, Route, Link等api,我們可以通過dom的事件控制路由浅缸。例如點擊一個按鈕進行跳轉(zhuǎn)枉疼,大多數(shù)情況下我們是這種情況皮假,所以在開發(fā)過程中鞋拟,我們更多是使用React-router-dom。安裝很簡單npm i react-router-dom --save,安裝了淘寶鏡像的就用cnpm吧惹资。
React Router 中文文檔 貌似不是最新的版本
React Router 英文文文檔
核心API
1.BrowserRouter
2.HashRouter
3.Route
4.Link
5.NavLink
6.MemoryRouter
7.Redirect
8.exact
9.Switch
10.withRouter
官方文檔解釋很詳細严卖,我就沒必要在new一次了,可以到官網(wǎng)學習具體用法布轿。
功能模塊
1.路由跳轉(zhuǎn)
<HashRouter>
<App>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</App>
</HashRouter>
App組件
import React, { Component } from 'react'
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
http://localhost:3000/#/哮笆,顯示Home組件內(nèi)容
http://localhost:3000/#/about,顯示About組件內(nèi)容
http://localhost:3000/#/contact汰扭,顯示Contact組件內(nèi)容
2.路由傳參和獲取
方法一:通過params
優(yōu)點:簡單快捷,并且稠肘,在刷新頁面的時候,參數(shù)不會丟失萝毛。
缺點:只能傳字符串项阴,并且,如果傳的值太多的話笆包,url會變得長而丑陋环揽。
如果,你想傳對象的話庵佣,可以用JSON.stringify(),想將其轉(zhuǎn)為字符串歉胶,然后另外的頁面接收后,用JSON.parse()轉(zhuǎn)回去巴粪。
**設置路由**
<Route path="/about/:id" component={About} />
**訪問方式**
<Link to={'/about/' + '2' }>About</Link>或者
this.props.history.push('/about/'+'2')
**about頁面獲取參數(shù)**
componentDidMount(){
console.log(this.props.match.params.id);
}
方法二:通過query
優(yōu)點:優(yōu)雅通今,可傳對象
缺點:刷新頁面,參數(shù)丟失
**訪問方式**
<Link to={{pathname:'/contact',query:{id:'456'}}}>contact</Link>或者
this.props.history.push({pathname :'/contact',query :{id:'456'}})
**contact頁面獲取參數(shù)**
componentDidMount(){
console.log(this.props.location.query.id);
}
方法三:通過state
優(yōu)點:優(yōu)雅肛根,可傳對象
缺點:刷新頁面辫塌,參數(shù)丟失
**訪問方式**
<Link to={{pathname:'/contact',query:{id:'456'}}}>contact</Link>或者
this.props.history.push({pathname :'/contact',query :{id:'456'}})
**contact頁面獲取參數(shù)**
componentDidMount(){
console.log(this.props.location.state.id);
}
備注:如果想要http://localhost:3000/#/contact?sort=name&type=1這種形式傳參
this.props.history.push({pathname :'/contact',search:'?sort=name&type=1',query :{id:'456'}})
**contact頁面獲取參數(shù)**
this.props.location.search取參數(shù),然后在進行解析
3.路由重定向與404
重定向:<Route exact path="/" render={() => (<Redirect to="/home"/>)}/>
<Route component={NoMatch}/>
路由指定的所有路徑?jīng)]有匹配時派哲,就會加載這個NoMatch組件臼氨,也就是404頁面
4.嵌套路由
寫法一:
<Route path="/home" render={() =>
<App>
<Route path="/home/second" component={Second} />
</App>
}/>
推薦寫法
在對應組件添加<Route path='/home/second' component={Second}/>
5.權(quán)限判斷
做管理后臺或者是其他項目,可能有部分頁面需要登錄才能訪問芭届,這就需要判斷有沒有登錄
const isAuthenticated = false; //判斷登錄
function PrivateRoute({ component: Component, ...rest }) {
return (
<Route {...rest} render={
props => isAuthenticated ? (<Component {...props} />) : (<Redirect to={{pathname: "/home"}}/>)
}/>
);
}
export default class router extends Component {
render() {
return (
<HashRouter>
<App>
<Switch>
<Route exact path="/" render={() => (<Redirect to="/home"/>)}/>
<Route path="/home" component={Home}/>
<Route path="/about/:id" component={About} />
<PrivateRoute path="/contact" component={Contact} />
<Route component={NoMatch} />
</Switch>
</App>
</HashRouter>
)
}
}
6.按需加載
網(wǎng)絡的一個重要特點是我們不必讓訪問者在使用它之前下載整個應用程序储矩。您可以將代碼拆分視為逐步下載應用程序。要做到這一點喉脖,我們將使用的WebPack椰苟,
@babel/plugin-syntax-dynamic-import
和react-loadable
抑月。
安裝:
npm i -D babel-plugin-syntax-dynamic-import
npm i -S react-loadable
實現(xiàn)按需加載核心代碼如下:
7.路由切換動畫
react-transition-group
教程相關代碼已上傳github树叽,如果幫助到你了麻煩點個star
react-router-demo