react中的路由:
react-router React中的路由的核心模块
react-router-dom React中的路由在浏览器端使用的模块 react-router-dom里面包含了react-router
react-router-native 在RN时,使用的路由模块 React-Native用来做原生APP
安装:npm i react-router-dom -S
是一个第三方的模块,不是react官方提供的。
参考网站:
https://reactrouter.com/web/guides/quick-start
https://serializedowen.com/docs/react-router-dom/%E5%90%91%E5%AF%BC/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B
http://react-guide.github.io/react-router-cn/docs/Introduction.html
路由:
一个url对应一个组件。
1) 引入路由
// Route 路由的出口,兼路由的规则 也是一个组件
// Router Route放在Router中 规定死的 是一个组件
// Link 类似于vue中的router-link
import {
Route, BrowserRouter as Router,Link } from "react-router-dom"
2) 使用
render() {
return (
<Router>
<Link to="/index">首页</Link>
<Link to="/movie">电影</Link>
<Link to="/threater">影院</Link>
<div>
{
/* Route表示路由的出口(是规则,也是出口) 类似于vue中的router-view */}
<Route path="/index" component={
Index }></Route>
<Route path="/movie" component={
Movie }></Route>
<Route path="/threater" component={
Threater }></Route>
</div>
</Router>
)
}
路由跳转的其他形式
1)
// 定义一个实现跳转的组件
const CustomLink = (props)=>{
return (
<li>
<Link to={
props.path}>{
props.name}</Link>
</li>
)
}
使用:
<CustomLink path="/" name="首页" />
2) NavLink:可以加样式
<NavLink to="/cart" activeClassName="selected">购物车</NavLink>
3)编程式导航
只有配置了Route组件,才会给对应的组件中传递history, location, match
现在就要使用history, location, match,怎么办?答:withRouter withRouter(Mine)
编程式路由 this.props.history.push(this.props.path)
switch、Redirect、严格匹配
一、
- Route 组件中可以不写component
- 一个路由,默认会匹配多个出口 如:/movie/hotshowing 它匹配到的出口有两个,一个是"/movie/hotshowing", 还有一个是"/movie/"
- 目标:就想匹配一个出口,第1个匹配到,后面就不要匹配了,此时就可以使用Switch组件
- 把所有的出口都放在Switch中,那么就只会匹配第1个
例如:
<Switch>
<Route path="/movie/hotshowing">
<h1>正在热映</h1>
</Route>
<Route path="/movie/commingsoon">
<h1>即将上映</h1>
</Route>
<Route path="/movie/">
<h1>正在热映</h1>
</Route>
</Switch>
二、
- exact="true"表示严格匹配 url需要和path长的一模一样 true可以不写
- 重定向组件:
<Redirect from="/" to="/index"></Redirect>
- path不写,默认就是path="*"
路由传参的两种形式
组件中可以直接打印this.props来获取参数
param传参:
传参:
<Route exact path="/threater/:id" component={
Threater }></Route>
接收:
this.props.match.params.id
query传参: ?name=‘wc’&age=100 叫查询字符串
传参:
<Redirect exact from="/" to="/index?name='wc'&age=100"></Redirect>
接收:
先new 一个 URLSearchParams
let result = new URLSearchParams(this.props.location.search)
console.log(result.get("name"));
注意: 在类组件中不能使用usexxxx
路由的守卫
<Route exact path="/cart" render={
()=>{
return this.state.isLogin ? <Cart /> :<Login dealLogin={
e=>this._dealLogin(e) }></Login>
} }></Route>