# React-router
**Repository Path**: weiyao11/react-router
## Basic Information
- **Project Name**: React-router
- **Description**: 学习react路由做的一个小demo
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2021-07-07
- **Last Updated**: 2021-07-07
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
#### 路由的基本使用
1. 明确好界面的导航区、展示区
2. 导航区的a 标签改为Link标签
`About`
3. 展示区写Route标签进行路径的匹配
``
4. 的最外侧包裹了一个``或``
#### 路由组件与一般组件
1. 写法不同:
一般组件: ``
路由组件: ``
2. 存放位置不同:.
一般组件: components
路由组件: pages
3. 接收到的props不同:
一般组件:写组件标签时传递了什么,就能收到什么
路由组件:接收到三个固定的属性
```js
history:
action: "PUSH"
block: ƒ block(prompt)
createHref: ƒ createHref(location)
go: ƒ go(n)
goBack: ƒ goBack()
goForward: ƒ goForward()
length: 50
listen: ƒ listen(listener)
location: {pathname: "/about", search: "", hash: "", state: undefined, key: "biwqw6"}
push: ƒ push(path, state)
replace: ƒ replace(path, state)
location:
hash: ""
key: "biwqw6"
pathname: "/about"
search: ""
state: undefined
match:
isExact: true
params: {}
path: "/about"
url: "/about"
```
#### NavLink与封装NavLink
1. NavLink可以实现路由连接的高亮,通过activeClassName指定样式名。
2. 标签体内容是一个特殊的标签属性
3. 通过this.props.children 可以获取标签体内容
#### Switch的使用
1. 通常情况下,path和component是一一对应的关系。
2. Switch 可以提高路由匹配效率(单一匹配)
#### 路由的严格匹配与模糊匹配
1. 默认使用的是模糊匹配(简单记: [ 输入的路径]必须包含要[匹配的路径],且顺序要-致)
2. 开启严格匹配:` `
3. 严格匹配不要随便开启,需要再开,有些时候开启会导致无法继续匹配二级路由。(注意)
#### 向路由组件传递参数
1. params 参数
1. params参数
路由链接(携带参数): `详情`
注册路由(声明接收): ``
接收参数: const {name,age} = this . props . match. params
2. search参数
路由链接(携带参数):` 详情`
注册路由(无需声明,正常注册即可):` `
接收参数: const {search} = this. props . location
备注:获取到的search是urlencoded编码字 符串,需要借助querystring解析
3. state参数
路由链接(携带参数):` 详情`
注册路由(无需声明,正常注册即可):` `
接收参数: this . props . location. state
备注:刷新也可以保留住参数。
#### router的push与replace模式
- 默认为push模式, 会存在history的历史记录
- replace 模式不会产生历史记录
```js
{ mapObj.title }
```
#### 编程式路由
```js
this.props.history.push(`/home/message/detail/${id}/${title}`)
this.props.history.replace(`/home/message/detail/${id}/${title}`)
```
借助this.props.history对象上的API对操作路由跳转、前进、后退
- this.props. history push()
- this.props.history replace()
- this.props.history goBack()
- this.props.history goForward()
- this.props.history.go()
#### withRouter的用法
withRouter 可以加工一般组件,将一般组件变成路由组件的问题
```js
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
class Header extends Component {
render() {
return (
React Router Demo
)
}
}
export default withRouter(Header)
```
#### BrowserRouter与HashRouter的区别
1. 底层原理不一样:
BrowserRouter使用的是H5的history API, 不兼容IE9及以下版本。
HashRouter使用的是URL的哈希值。
2. ur1表现形式不一-样
BrowserRouter的路径中没有#,例如: localhost:3000/demo/test
HashRouter的路径包含#,例如: localhost:3000/#/demo/test
3. 刷新后对路由state参数的影响
(1) BrowserRouter没有任何影响,因为state保 存在history对象中。
(2) HashRouter刷新后会导致路由state参数的丢失。!!!
4. 备注: HashRouter 可以用于解决一些路径错误相关的问题。