淺談react router路由庫
路由庫React Router,是react唯一的路由庫, 事實上也是唯一可選的路由庫。它通過管理 URL,實現元件的切換和狀態的變化。
上圖中,是我配置的一個router js檔案。
使用時,首先引入 npm install -save react-router-dom;
js檔案中使用時
import React from 'react'
import { Route, HashRouter, Switch } from 'react-router-dom'
router 本身只是一個容器,我們要將我們的路由url配置到Route元件中,
啟動專案時:http://localhost:3000/#/
當我們在訪問專案的時候,url後面會預設跟一個#,Router
元件有一個引數history
,它的值hashHistory
表示,路由的切換由URL的hash變化決定,即URL的#
部分發生變化,
當我們在進行路由跳轉時,hashRouter的執行是像下面這樣,
this.props.history.push(pathname: '/url',這裡可以跟傳入的引數),引數格式為 param{paramName: paramValue},
url中# 的作用,我在網上查了半天,也沒個說的,我自己的理解是:url 中“#”後面的部分,是配置在Route 元件中的,當我們點選對應的url時,會根據url的hash值,匹配Route 元件中的
如:
<Route exact path='/wizard' component={Wizard} />
當訪問wizard時,載入Wizard元件,當我們訪問wizard時,url的history的hash值就變成wizard的hash值,根據wizard的hash值去載入對應的component,也就是上圖中配置的Wizard元件
hashRouter 也可以這樣寫Router history={hashHistory}
Router history={browserHistory}這樣寫時,url後面就沒有#
二、巢狀路由
Route
<Router history={hashHistory}>//和hashRouter元件相同
<Route path="/" component={Parent}>
<Route path="/child1" component={Child1}/>
<Route path="/child1" component={Child2}/>
</Route>
</Router>
使用者訪問Child1時,要先訪問Parent元件,然後才訪問Child1,
parent元件中需要這樣寫:
export default React.createClass({
render() {
return <div> {this.props.children} </div>
}
})
上面程式碼中,Parent元件的this.props.children屬性就是子元件。
子路由也可以不寫在Router元件裡面,單獨傳入Router元件的routes屬性。
let routes = <Route path="/" component={Parent}>
<Route path="/child1" component={Child1}/>
<Route path="/child2" component={Child2}/>
</Route>;
<Router routes={routes} history={browserHistory}/>