目錄
擴展學習資料
?安裝和導入
Route匹配
@src/App.js
擴展學習資料
資料名稱 | 鏈接 | 備注 |
閱讀react router組件文檔 | https://react-router.docschina.org/web/guides/philosophy Introduction | React Router 中文文檔 | 擴展閱讀 |
路由鑒權 | React路由鑒權 - 掘金 | 無 |
React-Router v6 新特性解讀及遷移指南 | React-Router v6 新特性解讀及遷移指南_前端勸退師的博客-CSDN博客 |
?安裝和導入
// v6
npm install react-router-dom --save
- react-router 路由核心功能
- react-router-dom 基于【依賴】React-router,加入了一些在瀏覽器運行下的一些功能
基于瀏覽器開發的我們,只需要安裝react-router-dom就可以了
react-router-dom 提供的相關組件
- BrowserRouter(基于history Api) http://www.abc.com/article/a1
- hashRouter (#錨點路由) http://www.abc.com/#/article/a1
Route匹配
npm i react-router-dom@5.2.0
- Route
- 比較path屬性和當前地址的pathname。當一個匹配成功,它將渲染其內容,當它不匹配時就會渲染null
- Switch
- 一個會遍歷其所有的子元素,并僅渲染與當前地址匹配的第一個元素
- Link
- 使用作為url的導航,讓整個應用不刷新頁面在不同網址之間切換
@src/components/navbar.jsx
import React from 'react';
import { Link } from 'react-router-dom';
// 因為組件都打包到了bundle.js中,所以根據Link路由去判斷組件加載就不會請求網絡數據
const NavBar = () => {return (<ul><li>{/* 只加載局部組件 */}<Link to='/'>Home</Link></li><li><Link to='/products'>Products</Link></li><li><Link to='/posts/2018/06'>Posts</Link></li><li><Link to='/admin'>Admin</Link></li></ul>);
};
export default NavBar;
npm i react-router-dom@6.2.0
- Routes
- 替換Switch,更好用。
@src/App.js
import React, { Component } from 'react';
import NavBar from './components/navbar';
import Products from './components/products';
import Posts from './components/posts';
import Home from './components/home';
import Dashboard from './components/admin/dashboard';
// import ProductDetails from './components/productDetails';
// import NotFound from './components/notFound';
import { Route, Routes, Switch } from 'react-router-dom';
class App extends Component {render() {return (<div><NavBar /><div className='container'><Routes>{/* v6版本語法 */}<Route path='/products' element={<Products groupId="99" />} /><Route path='/posts' element={<Posts />} /><Route path='/admin' element={<Dashboard />} /><Route path='/' element={<Home />} />{/*v5版本語法 // <Switch> || exact只匹配第一個符合路由的組件<Route path='/' exact component={Home} /><Switch><Route path='/products' render={()=><Products?{...this.props} groupId="99" />} /></Switch>*/}</Routes></div></div>);}
}
export default App;
react-router v5文檔 中文文檔