路由安装
- win+r进入命令窗口,输入cmd
- cd到文件路径下
- 输入下面代码
npm i react-router-dom@5.0
路由组件
导入
import{HashRouter as Router,Route,NavLink,Redirect,Switch} from 'react-router-dom'
内容
HashRouter哈希路由 as起别名 router路由
BrowserRouter 浏览器路由 as Router
Route 存放路由的页面:path 路径,component组件,render渲染
<Route path="/" component={Home} exact></Route>
NavLink 导航链接:to为链接地址,exac为t精确匹配,匹配的链接会自动添加class active
<NavLink to="/" exact>首页</NavLink>
Redirect 重定向:例如需要登录后才能进入个人中心,点击用户中心就自动跳转到登录页面,这就是重定向。from表示从哪个路径,to表示定向到的路径。
<Redirect from='/admin' to="/admin/dash"></Redirect>
Switch 一次只匹配一个路由:例如404状态页,未使用Switch时无论是哪个页面都会显示,使用后,在Switch内的路径路径页面中就不会显示,在其他页面才会显示
<Switch>
<Route path="/" component={Home} exact></Route>
<Route path="/about" component={About}></Route>
<Route path="/details/:id" component={Details}></Route>
<Private path="/admin">
<Admin></Admin>
</Private>
<Route path="/admin" component={Admin}></Route>
<Route path="/login" component={Login}></Route>
{/* * 匹配任意路径 */}
<Route path="*" component={NoMatch}></Route>
</Switch>
路由props
match匹配的路由参数
- path路径
- url地址
- isExact 精确匹配
- params参数
history历史记录
go跳转
<button onClick={()=>history.go('/')}>首页</button>
goBack返回
<button onClick={()=>history.goBack('/')}>首页</button>
goForward 前进
<button onClick={()=>history.go('/')}>首页</button>
push插入
是在当前页面插入一个页面,点击后再返回可以回到点击按钮前一个页面
<button onClick={()=>history.goForward ('/')}>首页</button>
replace替换
是替换当前页面,点击后再返回可以回到点击按钮前第一个页面
<button onClick={()=>history.replace('/')}>首页</button>
listen监听
location
- pathname路径地址
- search查询
- hash哈希
- state状态
<NavLink to={{
pathname:"/details/abc",
search:"name=mumu&age=18",
hash:"good",
state:{reidrect:"/about"}
}}>详情abc</NavLink>
普通路由
<NavLink to=“/about”>
<Route path="/about" component={About}>
路由传参
<NavLink to=“/details/abc”>
<Route path="/details/:id" component={Details}>
获取参数
props.match.params.id
子路由
父路由Admin和普通是一样的
<NavLink to="/admin/dash">
<Route path="/admin/dash" component={Dash}>