react-router
开始
react-router 是对你前端路由的管理配置.
注意
React项目的可用的路由库是React-Router
,当然这也是官方支持的。它也分为:
react-router 核心组件
react-router-dom 应用于浏览器端的路由库(单独使用包含了react-router的核心部分)
react-router-native 应用于native端的路由
我用的web端路由库:
1 | { |
具体看官方网站 https://reacttraining.com/react-router/web/guides/quick-start.
安装
1 | npm install --save react-router-dom |
简单使用
示例:比如一个页面有导航栏跟内容.
index-router.js
: 主页面
1 | import React, { Component } from 'react'; |
现在我们主页有一个导航栏,Link标签是来自react-router-dom
.
这样形成的效果为:
这里用到了 Link, Switch, Router,Route.
react-router-dom组件
Link
替代了<a/>
标签,而且比其更多的扩展.
属性to
来指向要跳转的地方,可以是字符串,可以是对象,可以是一个function.
当是字符串的时,字符串要指向跳转的地址location,第一个斜杠加不加结果都一样.
1 | <Link to='about'/> |
当是对象的时候,与字符串的时候有了更多的扩展,对象结构有:
1 | { |
示例:
1 | import React from 'react'; |
效果:
对于state
,关于官方的解释我也是一知半解,总之它会把该数值传给About
组件,在props
的location
中存着:
从图可知,to中的对象都在location里存着.
Router
The common low-level interface for all router components. Typically apps will use one of the high-level routers instead.
就是说Router只是一个所有router组件的公共接口,要使用则用它的实现类组件:
<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>
这里我们只讲前两种.
BrowseRouter
就是我们常见的url,history模式.
你可能也注意到了我们之前用得都是这个 Router,它得路径就是斜杠加路径完事.
但是它也有几个参数,
1 | { |
1 | import React from 'react'; |
此时设置的根路径是:/browser,
HashRouter
这种Router模式是hash模式.不像之前直接后面跟斜杠路径,而是hash值.
配置项:
1 | { |
示例: 默认 hashType
1 | import React from 'react'; |
默认 hashType模式 slash.
示例: noslash
两种类型区别就在于多了一个斜杠.
Route
The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when its path
matches the current URL.
必须与Router一起使用,然后会在Router里去匹配地址,找到Route.
从之前例子中我们可以看出来,Route相当于二级路径.
props
对于Route的props有:
- match
- location
- history
首先match是有关路径上的参数:
1 | import React from 'react'; |
1 | import React from 'react'; |
其他信息:
至于history,就是提供了历史前进后退得函数.
push(path, [state])
- 跳转到指定路径replace(path, [state])
- 直接替换路径go(n)
- 历史前进几步goBack()
- 历史后退几步goForward()
- 相当于 go(1).
exact属性
路径匹配的严格程度.
path | location.pathname | exact | matches? |
---|---|---|---|
/one |
/one/two |
true |
no |
/one |
/one/two |
false |
yes |
sensitive属性
表示是否大小写敏感.
Switch
Renders the first child <Route>
or <Redirect>
that matches the location.
就是说如果有多个路由匹配一样,那么只会渲染第一个route
.
示例:
不用switch:
1 | import React from 'react'; |
这里同一个地址,我们有两个组件,我们没有用 Switch
结果会是这样,两个都显示:
使用 switch:
1 | import React from 'react'; |
结果会是这样,只会渲染第一个:
Hook 钩子
react-router-dom 中提供了一些方法.
- useHistory
- useLocation
- useParams
- useRouteMatch
这些可以获取其对象,其实也可以通过props获取到.
示例:
1 | import { useHistory } from 'react-router-dom'; |
- 本文作者: Veng
- 本文链接: http://veng0923.github.io/2020/04/03/react-router/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!