1.安裝react-router-dom
1.1 在項目命令行中,執行
npm install react-router-dom-S
下載到生產環境依賴中。
2.路由內置組件
HashRouter
表示一個路由的跟容器,將來所有跟路由相關的東西,都要包裹在HashRouter中,一個網站中,只需要使用一次HashRouter就好了。
Link
表示一個路由的連接;
Route
表示一個路由規則;
1 render(){ 2 return ( 3 <HashRouter> 4 <div> 5 <h1>這是網站的根目錄</h1> 6 <hr /> 7 <Link to="/new">首頁</Link> 8 <Link to="/movie/">新聞</Link> 9 <Link to="/about">關於我們</Link> 10 <hr /> 11 <Route path="/home" component={HOME} ></Route><hr/> 12 <Route path="/new" component={New} exact></Route><hr/> 13 <Route path="/about" component={About}></Route><hr/> 14 </div> 15 </HashRouter> 16 ); 17 }
由Route創建的標簽,就是路由規則,其中path表示要匹配的路由,component表示要展示的組件。
Route具有兩種身份:
1.它是一個路由匹配規則;
2.它是一個占位符,表示將來匹配到的組件都放到這個位置
注意:
Link to屬性的地址也是/開頭,Link在頁面渲染的是a標簽;
Route 組件path地址是以/開頭 ,配置component屬性,是顯示的組件,這個屬性不可以大寫;
3.嵌套路由
嵌套路由:在路由組件中,使用Link,Route,配置子路由,實現跳轉,切換;
下面為一級路由,在一級路由New為路由組件
1 <Route path="/new" component={ New }></Route> 2 3 render (){ 4 return( 5 <React.Fragment> 6 《新聞》 7 <ul> 8 <li> 9 <Link to="/new/act">今日聚焦</Link> 10 </li> 11 <li> 12 <Link to="/new/three">三農信息</Link> 13 </li> 14 <li> 15 <Link to="/new/week">新聞周刊</Link> 16 </li> 17 </ul> 18 <Route path="/new/act" component={Act}></Route> 19 <Route path="/new/three" component={Three}></Route> 20 <Route path="/new/week" component={Week}></Route> 21 22 </React.Fragment> 23 ) 24 }
4.帶參數路由和獲取參數
通過配置路由的地址,在Link跳轉時
Route path路徑后面 /:id (key)
Link to 路徑后面 /top/10 (value)
接收傳值:
class類組件,this.props.match.params.屬性名
函數組件:形參.match.params.屬性名
代碼實例:
1 render(){ 2 return ( 3 <HashRouter> 4 <div> 5 <h1>網站根目錄</h1> 6 <hr /> 7 <Link to="/about/add/5497">關於我們</Link> 8 <hr /> 9 <Route path="/about/:type/:id" component={Movie} exact></Route> 10 </div> 11 </HashRouter> 12 ); 13 }
在Route內置組件中,配置path地址
1 <Route path="/about/:type/:id" component={Movie}></Route> 2 3 //在Link內置組件中,配置to屬性,進行跳轉: 4 5 <Link to="/about/active/5497"></Link> 6 7 //類組件中通過聲明周期進行接收this.props傳遞過來的數據 8 9 render(){ 10 console.log(this); 11 return ( 12 <div> 13 電影--{this.props.match.params.type}--{this.props.match.params.id} 14 </div> 15 ); 16 }
5. HashRouter和BrowserRouter的區別
React-Router 是建立在 history 之上的,常見的history路由方案有三種形式,分別是:
- hashHistory
- hashHistory 使用 URL 中的 hash(#)部分去創建路由,舉例來說,用戶訪問http://www.example.com/,實際會看到的是http://www.example.com/#/。
- browserHistory
- browserHistory 是使用 React-Router 的應用推薦的 history方案。它使用瀏覽器中的 History API 用於處理 URL,創建一個像example.com/list/123這樣真實的 URL
- 當刷新頁面時,瀏覽器會向服務器請求,服務器實際會去找根目錄下對應的文件,發現找不到,因為實際上我們的服務器並沒有這樣的 物理路徑/文件 或沒有配置處理這個路由,所有內容都是通過React-Router去渲染React組件,自然會報404錯誤。
- createMemoryHistory
- Memory history 不會在地址欄被操作或讀取。這就解釋了我們是如何實現服務器渲染的。同時它也非常適合測試和其他的渲染環境(像 React Native )。和另外兩種history的一點不同是你必須創建它,這種方式便於測試。
兩種解決方法
- 使用hashHistory,不用做額外處理
- 使用browserHistory,服務器需要進行相關路由配置
方法見這里
