安装
npm install react-router-dom@5
路由的基本使用
- 明确界面中导航区、标签区
- 导航区的a标签改为Link组件
<link to='/about'>关于<Link>
- 展示区写Route组件进行路径的匹配
<Route path="/about" component={About}></Route>
<App>
的最外层包裹一个<BrowserRouter>
或<HashRouter>
路由组件和一般组件
- 写法不同
- 存放位置不同(规范做法中),一般组件放在components,路由组件放在pages
- 接受到props不同 一般组件:写组件标签时传递了什么,就能收到什么 路由组件:
history: {
go: ƒ go(n)
goBack: ƒ goBack()
goForward: ƒ goForward()
push: ƒ push(path, state)
replace: ƒ replace(path, state)
}
location: {
hash: ""
pathname: "/about"
search: ""
}
match: {
params: {}
path: "/about"
url: "/about"
}
Switch的使用
- 通常请款下,path和componet是一一对应的
- Switch可以提高路由匹配效率(单一匹配)
<Switch>
<Route path="/about" component={About}/>
<Route path="/home" component={Home}/>
<Route path="/todo" component={Todo}/>
</Switch>
解决多级路径刷新页面样式丢失的问题
- public/index.html 中引入样式不写
./
写/
(常用) - public/index.html 中引入样式不写
./
写%PUBLIC_URL%
(常用) - 使用HashRouter
路由的严格匹配和模糊匹配
- 默认请使用的是模糊匹配(输入路径必须包含匹配路径,且顺序一致)
- 开启严格模式
<Route exact={true} path='about' component={About}/>
- 严格匹配不要随意开启,需要再开,有时候开会导致无法继续匹配二级路由
Redirect的使用
- 一般卸载路由注册的最下方,当所有的路由都无法匹配是,跳转到Redirect指定的路由
- 具体编码
<Switch>
<Route path="/about" component={About}/>
<Route path="/home" component={Home}/>
<Route path="/todo" component={Todo}/>
<Redirect to="/about"></Redirect>
</Switch>
嵌套路由
- 注册资路由时要协商父路由的path值
- 路由的匹配时按咋后注册路由的顺序进行的
向路由组件传递数据
- paras参数
- 路由链接(携带参数):
<Link to={
/home/message/detail/${mes.id}}>{mes.text}</Link>
- 注册路由(声明参数):
<Route path="/home/message/detail/:id" component={MessageDetail}></Route>
- 接受参数:
const {id} = this.props.match.params;
- 路由链接(携带参数):
- search参数
- 路由链接(携带参数):
<Link to={
/home/message/detail?id=${mes.id}}>{mes.text}</Link>
- 注册路由(无需声明,正常注册即可):
<Route path="/home/message/detail" component={MessageDetail}></Route>
- 接受参数:
const {id} = this.props.location.search;
- 备注:获取到的seach时urlencode编码字符串,需要借助querystring解析
- 路由链接(携带参数):
- state参数
-
路由链接(携带参数):
<Link to={{path: '/home/message/detail', state: {id: mes.is}}}>{mes.text}</Link>
-
注册路由(无需声明,正常注册即可):
<Route path="/home/message/detail" component={MessageDetail}></Route>
-
接受参数:
const {id} = this.props.location.state;
-
备注:刷新也可以保留参数,但是清除浏览器缓存后,参数不可保留
-
BrowserRouter和HashRouter的区别
- 底层原理不一样
- BrowserRouter使用的是H5的histroy API,不兼容IE9及以下版本
- HashRouter使用的是URL的哈希值
- path表现不一样
- BrowserRouter的路径中没有#,例如:localtion:3000/home
- HashRouter的路径包含#,例如:localtion:300/#/home
- 刷新后对路由state参数的影响
- BrowserRouter没有任何影响,因为state保存在history对象中
- HashRouter刷新后回导致路由state参数的丢失