一、路由的基本使用
- 明确好界面中的导航区、展示区
- 导航区的
a
标签改为Link
组件
<Link to="/xxxx">Demo</Link
- 展示区写
Route
组件进行路径的匹配
<Route path="/xxxx" component={Demo} />
<App>
最外层包裹一个<BrowserRouter>
或<HashRouter>
二、路由组件与一般组件
-
写法不同
一般组件:<Demo /> 路由组件:<Route path="/demo" component={Demo} />
-
存放位置不同
一般组件:components文件夹下 路由组件:pages文件夹下
-
接收到的props不同
一般组件:写组件标签时传递了什么,就能收到什么 路由组件:接收到三个固定的属性: history: { action, go, goBack, goForward, length, listen, location, push, replace } location: { pathname, search, state } match: { params, path, url }
三、NavLink与封装NavLink
NavLink
可以实现路由链接的高亮,通过activeClassName
指定样式名- 标签体内容是一个特殊的标签属性
- 通过
this.props.children
可以获取标签体内容
四、Switch的使用
- 通常情况下,
path
和component
是一一对应的关系 Switch
可以提高路由匹配效率(单一匹配)
五、解决多级路径刷新页面样式丢失的问题
public/index.html
中引入样式时不写./
写/
(常用)public/index.html
中引入样式时不写./
写%PUBLIC_URL%
(常用)- 使用
HashRouter
六、路由的严格匹配与模糊匹配
- 默认使用的模糊匹配(简单记:输入的路径 必须包含 要匹配的路径,且顺序一致)
- 开启严格模式:
<Route exact path="/about" component={About} />
- 严格匹配不要随便开启,需要时再开,有些时候开启会导致无法继续匹配二级路由
七、Redirect的使用
-
一般写在所有路由组件注册的最下方,当所有路由都无法匹配时,跳转到
Redirect
指定的路由 -
具体的编码:
<Switch> <Route path="/about" component={About} /> <Route path="/home" component={Home} /> <Redirect to="/about" /> <Switch/>
八、嵌套路由
- 注册子路由时要写上父路由的
path
值 - 路由的匹配是按照注册路由的顺序进行的
九、向路由组件传递参数
-
params
参数路由链接(携带参数):`<Link to={"/demo/test/tom/18"}>详情< /Link>` 注册路由(声明接收):`<Route path="/demo/test/:name/:age" component={Test} />` 接收参数:`const { name, age } = this.props.match.params`
-
search
参数路由链接(携带参数):`<Link to={"/demo/test?name=tom&age=18"}>详情< /Link>` 注册路由(无需声明,正常注册即可):`<Route path="/demo/test" component={Test} />` 接收参数:`const { search } = this.props.location` 备注:获取到的search是urlencode编码的字符串,需要借助querystring解析
-
state
参数路由链接(携带参数):`<Link to={{pathname:"/demo/test", state:{name:"tome",age:18}}}>详情< /Link>` 注册路由(无需声明,正常注册即可):`<Route path="/demo/test" component={Test} />` 接收参数:`const { name, age } = this.props.location.state` 备注1:刷新也可以保留住参数 备注2:当to为对象时,浏览器的history的action为replace,根据react-router5源码中解释: 当replace和isDuplicateNavigation两者其中之一为true时就会执行history.replace方法,而to为对象时,resolveToLocation和normalizeToLocation返回的都是to对象,即isDuplicateNavigation为ture,执行history.replace,所以浏览器的历史记录被replace了
十、编程式路由导航
push(path:string, state:{})
replace(path:string, state:{})
十一、BrowserRouter与HashRouter的区别
-
底层原理不一样:
BrowserRouter使用的是H5的history API,不兼容IE9及以下版本 HashRouter使用的是URL的哈希值
-
url
的表现形式不一样BrowserRouter的路径中没有#,例如localhost:3000/demo/test HashRouter的路径包含#,例如localhost:3000/#/demo/test
-
刷新后对路由
state
参数的影响BrowserRouter没有任何影响,因为state保存在history对象中 HashRouter刷新后会导致路由state参数的丢失
-
备注:
HashRouter
可以用于解决一些路径错误相关的问题
十二、withRouter的使用注意
withRouter
是一个高阶函数hoc
,接收一个一般组件为参数,返回一个新的组件,使得其带有history、location、match路由组件的三大参数- 简单来说就是可以加工一般组件,让一般组件具备路由组件所特有的API
- 返回值是一个新组件