1.安装
react-router是核心库,在项目中不需要安装,web开发只需安装react-router-dom、native开发安装react-router-native。
非路由挂载的组件如果想使用history,match,location时需要使用withRouter高阶组件,
import { withRouter } from 'react-router-dom'
2.url参数携带与获取
Url-regex-path |
url |
挂载组件获取url参数 |
/product/:id |
/product/xxx |
this.props.match.params.id |
/article |
/article?id=xxx |
this.props.location.search 该属性的值为?id=1 |
this.props.history.push('/article',{id:5566})携带的数据在组件中通过this.props.location.state.id获取
3.Route组件的exact和strict
路由匹配的本质实际是拿window.loaction.pathname去与Route.path这个正则表达式做判断,也就是url中的问号不会影响匹配结果,因为url中的问号及后面的信息存储在window.location.pathname中
exact如果为true时,表示Route.path与location.pathname是相等关系(相等判断前先忽略Route.path结尾的/,忽略location.pathname结尾的一个反斜杠)
url-regex-path |
url |
是否匹配 |
/product或/product/ |
/product |
是 |
/product/ |
是 |
|
/product?id=xxx |
是 |
|
/product// |
否 |
|
/product/xxx |
否 |
strict为true时,表示location.pathname包含Route.path中的内容就行,Route.path结尾的反斜杠将做为匹配依据。
url-regex-path |
url |
是否匹配 |
/product/ |
/product |
否 |
/product/ |
是 |
|
/product// |
是 |
|
/product/xxx |
是 |
4.path通配符
/hello/:name
匹配 /hello/car
匹配 /hello/bus
/hello/:name?
匹配 /hello
匹配 /hello/car
匹配 /hello/bus
5.react-router-config配置文档
6.react-router文档