下載react-router-dom
路由:不同的路由
npm i react-router-dom --save
App.js文件中引入路由相關的模塊
import React from 'react';
/**HashRouter規(guī)定路由的形式:路由是#/的形式
http://localhost:3000/#/main/home**/
import { HashRouter as Router, Link, Route, Redirect,Switch } from 'react-router-dom';
import Home from './Home';
import LifeCircle from './LifeCircle';
function App() {
return (
<>
<Router basename='/main'>
<Link to={{pathname:'/home',search:"?id=1",hash:'#abc',state:{msg:'123'}}}>首頁</Link>
<Link to='/lifecircle/123'>生命周期</Link>
<Route path='/home' exact component={Home}></Route>
<Route path='/lifecircle/:id' exact component={LifeCircle}></Route>
<Redirect path='/' to='/home'></Redirect>
</Router>
</>
);
}
export default App;
或者
import React from 'react';
/**BrowserRouter規(guī)定路由的形式:需后端配合使用
http://localhost:3000/main/home **/
import { BrowserRouter as Router, Link, Route, Redirect,Switch} from 'react-router-dom';
import Home from './Home';
import LifeCircle from './LifeCircle';
function App() {
return (
<>
<Router basename='/main'>
<Link to={{pathname:'/home',search:"?id=1",hash:'#abc',state:{msg:'123'}}}>首頁</Link>
<Link to='/lifecircle/123'>生命周期</Link>
<Route path='/home' exact component={Home}></Route>
//動態(tài)路由:id就是動態(tài)參數(shù),可以在頁面的props.match.params中獲取
<Route path='/lifecircle/:id' exact component={LifeCircle}></Route>
<Redirect path='/' to='/home'></Redirect>
</Router>
</>
);
}
export default App;
Router相當于一個容器,用來包裹Route,Link,Redirect等路由組件
- basename:定義路由的基礎路徑,當點擊'生命周期'進行跳轉時路由地址會變?yōu)椋?main/lifecircle
Link:組件相當于a標簽,用于頁面跳轉
- to后面可以是字符串,直接跟跳轉的路由地址
- to后面也可以是對象
- pathname:路由地址
- search:在路由地址中添加參數(shù)
- hash:在路由中拼接hash值
- state:傳遞參數(shù)給即將跳轉的頁面,可以在組件的props.location中獲取到
- replace:即將跳轉的路由地址替換當前路由地址
Route定義不同的路由加載不同的內(nèi)容
- path:定義路由地址
- component :定義加載的組件
比如:訪問/main時會加載Home組件 - exact:精準匹配路由
當我們有路由/和/home時,如果不精準匹配路由時,當訪問/home時也會加載/這個路由
Switch只顯示匹配到的第一個路由
Switch匹配到第一個路由就不會繼續(xù)匹配了,
如果不加Route 里不加 exact,那么凡是Link里面 to 的路徑包含了/,
那么就會被匹配到,于是Switch就不繼續(xù)匹配下去
react 404 頁面的處理
<Route path="*" component={404組件}></Route>
事件跳轉
- 函數(shù)組件和類組件都可以通過props.history對象下提供到的方法進行跳轉
- props.history.push('路徑')
- props.history.replace('路徑')
- props.history.go()
- props.history.goBack()
- props.history.goForward()
- 函數(shù)組件還可以根據(jù)react-router-dom提供的新方法進行跳轉
import {useHistory} from 'react-router-dom'
在函數(shù)組件的return前面聲明
const router = useHistory()
router對象下的方法同props.history