路由(router)
后端路由:根据用户的请求返还不通的内容
前端路由:根据不同的url 去切换组件
安装
npm install react-router-dom
两种模式
1)历史纪录模式 BrowserRouter
2) hash模式 HashRouter
用法
1)在跟组件引入
```bash
import {BrowserRouter as router} from 'react-router-dom'
```
2)包裹跟组件
```html
<Router>根组件</Router>
```
3)在用到路由的组件里引入
```bash
import {Route} from 'react-router-dom'
```
4)路由和path跳转设置
```html
<Route path="xxx" component={组件} />
```
5)用Link组件和NavLink实现跳转,Link和NavLink的区别是NavLink是默认选中带有默认类名active
```html
<Link to="path">yyy</Link>
<NavLink to="path">yyy</NavLink>
```
路由切换的组件有三个属性(props)
1) history
2) location
3) match
exact 精确匹配
Redirect 重定向
404 页面的设置
在最下面放入一个组件只有componponent属性没有path属性,以上路由都没匹配上的时候跳转默认匹配最后一个组件
<Route component={组件} />
Switck
在Link外面包裹一个Switck标签可以使多组件匹配时只渲染第一个所匹配的组件
监控路由的变化 history.listen
withRouter
作用是让不是路由切换的组件也具有路由切换组件的三个属性(location match history)
监控路由的变化 this.propos.history.listen((location)=>{
//locatin.pathname 会根据路由的变化而变化
})
解决刷新 在constructor里又调用了一次函数 把 this.props.location.pathname传入
监控路由参数的变化(路由传参)
Link to="/xxx/实参/实参2"
path /xxx/:参数/:参数2/... 这叫路由的参数
接收参数: this.props.math.params.参数
编程式导航
this.props.history.push(path)
this.props.history.push listen go… 适合做编程式导航和监听路由的变化
2) match 取路由的参数
3) location
location.pathname
location.search(取查询字符串) ?a=xxx&b=yyy
location.searc.slice(1) 去问号
备注:
import qs from 'querystring'//一个键值对转对象的工具,使取值更方便,用法如下
qs.parse(a=xxx&b=yyy) {a:xxx,b:yyy}
传递多个值
location.state