React-router 工作学习总结
学习目的:为单页面react的应用提供页面间的切换,即路由切换
相关内容:
- 此工具由 Facebook 开发并维护。
- 官网地址:https://reacttraining.com/react-router/web/guides/philosophy
- 安装地址:https://www.npmjs.com/package/react-router-dom(使用 npm or yarn.)
- 学习地址:https://www.jianshu.com/p/e3adc9b5f75c
- 学习地址:https://css-tricks.com/react-router-4/
http://blog.csdn.net/sinat_17775997/article/details/78387001 (后期总结)
- 使用
create-react-app
创建一个React web 应用 - Static router(静态路由)
- Ddynamic Routing(动态路由)
- Nested Routes (嵌套路由)
- Responsive Routes(响应式路由)
- 学习的版本是4.2.2 (is the latest of 16 releases)
一、Installation
//using npm
npm install --save react-router-dom
//code
import { BrowserRouter, Route, Link } from 'react-router-dom'
二、API
A、组件
1.<BrowserRouter>
- 决定你路由器的类型
一个使用了 HTML5 history API 的高阶路由组件,保证你的 UI 界面和 URL 保持同步。此组件拥有以下属性:
1) basename : (string)
作用:为所有位置添加一个基准URL
使用场景:假如你需要把页面部署到服务器的二级目录,你可以使用 basename 设置到此目录。
<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">
2) getUserConformation : (function)
作用:导航到此页面前执行的函数,默认使用 window.confirm
使用场景:当需要用户进入页面前执行什么操作时可用,不过一般用到的不多。
3) forceRefresh : (bool)
作用:当浏览器不支持 HTML5 的 history API 时强制刷新页面。
使用场景:同上。
4) keyLength : (number)
作用:设置它里面路由的 location.key 的长度。默认是6。(key的作用:点击同一个链接时,每次该路由下的 location.key都会改变,可以通过 key 的变化来刷新页面。)
使用场景:按需设置。
5) children : (node)
作用:渲染唯一子元素。
使用场景:作为一个 Reac t组件,天生自带 children 属性。
注意:<BrowserRouter>
只能有一个子元素
2.<Link>
我们应用需要在各个页面(每一个页面就是一个路由)间切换。如果使用锚点元素(就是)实现,在每次点击时页面将被重新加载。React Router提供了<Link>
组件用来避免这种状况的发生。当你点击时,URL会更新,组件会被重新渲染,但是页面不会重新加载。
1)link
组件 使用 to
属性进行链接,可以是字符串也可以是对象
-to: string
作用:跳转到指定路径
使用场景:如果只是单纯的跳转就直接用字符串形式的路径。
<link to="/course">
-to: object
作用:携带参数跳转到指定路径
作用场景:比如你点击的这个链接将要跳转的页面需要展示此链接对应的内容,又比如这是个支付跳转,需要把商品的价格等信息传递过去。
<Link to={{
pathname: '/courses',
search: '?sort=name',
hash: '#the-hash',
state: { price: 18 }
}}/>
import { Link } from 'react-router-dom'
const Header = () => (
<header>
<nav>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/roster'>Roster</Link></li>
<li><Link to='/schedule'>Schedule</Link></li>
</ul>
</nav>
</header>
)
2)replace: bool
为 true 时,点击链接后将使用新地址替换掉上一次访问的地址,什么意思呢,比如:你依次访问 ‘/one’ ‘/two’ ‘/three’ ’/four’ 这四个地址,如果回退,将依次回退至 ‘/three’ ‘/two’ ‘/one’ ,这符合我们的预期,假如我们把链接 ‘/three’ 中的 replace 设为 true 时。依次点击 one two three four 然后再回退会发生什么呢?会依次退至 ‘/three’ ‘/one’!
注意:<Link to>
等价于 history.push('')
3.Route
组件
Route 组件是React Router 中最重要的组件了
它最基本的职责就是当页面的访问地址与 Route 上的 path 匹配时,就渲染出对应的 UI 界面。
1)Route render methods(3)
<Route component>
<Route render>
<Route children>
–component–
只有当访问地址()和路由匹配时,一个 React component 才会被渲染,此时此组件接受 route props (match, location, history)。
当使用 component 时,router 将使用 React.createElement 根据给定的 component 创建一个新的 React 元素。
这意味着如果你使用内联函数(inline function)传值给 component 将会产生不必要的重复装载。对于内联渲染(inline rendering), 建议使用 render prop。
<Route path="/user/:username" component={User} />
const User = ({ match }) => {
return <h1>Hello {match.params.username}!</h1>
}
–render–
// 内联渲染
<Route path="/home" render={(props) => <h1>Home</h1} />
注:每种 render method 都有不同的应用场景,同一个
<Route>
应该只使用一种 render method
,大部分情况下你将使用 component 。所有的 render method 无一例外都将被传入这些 props.Route Props(this.props) props分别是:
match location history
只有当访问地址和路由匹配时,一个 React component
才会被渲染,此时此组件接受 route props (match, location, history)。
2)path: string
任何可以被 path-to-regexp解析的有效 URL 路径
如果不给path,那么路由将总是匹配。
3)exact: bool
如果为 true,path 为 ‘/one’ 的路由将不能匹配 ‘/one/two’,反之,亦然。
4)strict: bool
对路径末尾斜杠的匹配。如果为 true。path 为 ‘/one/’ 将不能匹配 ‘/one’ 但可以匹配 ‘/one/two’。
注:
如果要确保路由没有末尾斜杠,那么 strict 和
exact 都必须同时为 true
4.<NavLink>
组件
这是 <Link>
的特殊版,顾名思义这就是为页面导航准备的。因为导航需要有 “激活状态”。
1)activeClassName属性: string
导航选中激活时候应用的样式名,默认样式名为 active
<NavLink
to="/about"
activeClassName="selected"
>MyBlog</NavLink>
2)activeStyle属性: object
如果不想使用样式名就直接写style
3)exact属性: bool
若为 true,只有当访问地址严格匹配时激活样式才会应用
4)strict属性: bool
若为 true,只有当访问地址后缀斜杠严格匹配(有或无)时激活样式才会应用
5)isActive: func
决定导航是否激活,或者在导航激活时候做点别的事情。不管怎样,它不能决定对应页面是否可以渲染。
<NavLink
to="/about"
activeStyle={{ color: 'green', fontWeight: 'bold' }}
>MyBlog</NavLink>
5.<Switch>
组件
只渲染出第一个与当前访问地址匹配的 <Route>
或 <Redirect>
。
思考如下代码,如果你访问 /about,那么组件 About User Nomatch 都将被渲染出来,因为他们对应的路由与访问的地址 /about 匹配。这显然不是我们想要的,我们只想渲染出第一个匹配的路由就可以了,于是 应运而生!
<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>
children属性: node
<Switch>
下的子节点只能是 <Route>
或 <Redirect>
元素。只有与当前访问地址匹配的第一个子节点才会被渲染。<Route>
元素用它们的 path 属性匹配,<Redirect>
元素使用它们的 from 属性匹配。如果没有对应的 path 或 from,那么它们将匹配任何当前访问地址。
<Fade>
<Switch>
{/* 用了Switch 这里每次只匹配一个路由,所有只有一个节点。 */}
<Route/>
<Route/>
</Switch>
</Fade>
6.Prompt
组件 - 在用户输入信息方面很重要,以防信息遗漏
当用户离开当前页面前做出一些提示。
1)message属性: string
当用户离开当前页面时,设置的提示信息。
<Prompt message="确定要离开?" />
2)message属性: func
当用户离开当前页面时,设置的回掉函数
<Prompt message={location => (
`Are you sue you want to go to ${location.pathname}?`
)} />
3)when属性: bool
通过设置一定条件要决定是否启用 Prompt
7.<Redirect>
组件
渲染时将导航到一个新地址,这个新地址覆盖在访问历史信息里面的本该访问的那个地址。
to: string
重定向的 URL 字符串
to: object
重定向的 location 对象
push: bool
若为真,重定向操作将会把新地址加入到访问历史记录里面,并且无法回退到前面的页面。
from: string
需要匹配的将要被重定向路径。
用法:
//1.用户需要登陆后才能看到主页:(authed表示是否登录)
const PrivateRoute = ({ component: Component, authed ,...rest}) => (
<Route
{...rest}
render={ props => (
authed === true ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/signin',
state: { from: props.location }
}}/>
)
)}/>
);
//2.多个Route定义哪一个显示
<Switch>
<Route path="/module" component={Module}/>
<Route path="/reader" component={Reader} />
<Route path="/edit" component={Edit}/>
<Redirect to="/module"/>
</Switch>
注意:<Redirect to="">
相当于history.replace('')
8.Router
组件
所有路由器组件的通用底层接口。
通常,应用程序将使用其中一个高级路由器:
<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>
注: 使用低级别<Router>
的最常见用法是将自定义历史与Redux或Mobx等状态管理库同步。请注意,与React Router一起使用状态管理库并不是必需的,它仅用于深度集成。
1)history 属性 - 对象
一个用于导航的history对象
history相关介绍
2)能包含children node
<Router>
<App/>
</Router>
B、对象和方法
先前说明:history location match属性一旦路由状态和路经一致,就会在<Route component ={myCompoent}>
渲染component时,传入至component的props对象中,
1.history
histoty 是 React Router 的两大重要依赖之一(另一个当然是 React 了),在不同的 javascript 环境中, history 以多种能够行驶实现了对会话(session)历史的管理。
1)我们会经常使用以下术语:
“browser history” - history 在 DOM 上的实现,用于支持 HTML5 history API 的浏览器
“hash history” - history 在 DOM 上的实现,用于旧版浏览器。
“memory history” - history 在内存上的实现,用于测试或非 DOM 环境(例如 React Native)。
2)history 对象通常具有以下属性和方法:
length: number 浏览历史堆栈中的条目数 (history.length
)
action: string 路由跳转到当前页面执行的动作,分为 PUSH, REPLACE, POP
location: object 当前访问地址信息组成的对象,具有如下属性:
- pathname: string URL路径
- search: string URL中的查询字符串
- hash: string URL的hash 片段
- state: string 例如执行 push(path, state) 操作时,location 的 state
将被提供到堆栈信息里,state 只有在 browser 和 memory history 有效。
push(path, [state]) 在历史堆栈信息里加入一个新条目。
replace(path, [state]) 在历史堆栈信息里替换掉当前的条目
go(n) 将 history 堆栈中的指针向前移动 n。
goBack() 等同于 go(-1)
goForward 等同于 go(1)
注:history 对象是可变的,因为建议从 <Route>
的 prop 里来获取 location,而不是从 history.location 直接获取。这样可以保证 React 在生命周期中的钩子函数正常执行,例如以下代码:
class Comp extends React.Component {
componentWillReceiveProps(nextProps) {
// locationChanged
const locationChanged = nextProps.location !== this.props.location
// 错误方式,locationChanged 永远为 false,因为history 是可变的
const locationChanged = nextProps.history.location !== this.props.history.location
}
}
2.match
match 对象包含了 <Route path>
如何与 URL 匹配的信息,具有以下属性:
params: object 路径参数,通过解析 URL 中的动态部分获得键值对
isExact: bool 为 true 时,整个 URL 都需要匹配
path: string 用来匹配的路径模式,用于创建嵌套的 <Route>
url: string URL 匹配的部分,用于嵌套的 <Link>
在以下情境中可以获取 match 对象
在 Route component 中,以 this.props.match获取
在 Route render 中,以 ({match}) => () 方式获取
在 Route children 中,以 ({match}) => () 方式获取
在 withRouter 中,以 this.props.match的方式获取
matchPath 的返回值
当一个 Route 没有 path 时,它会匹配一切路径。
3.location - 对象
location 是指你当前的位置,将要去的位置,或是之前所在的位置
{
key: 'sdfad1'
pathname: '/about',
search: '?name=minooo'
hash: '#sdfas',
state: {
price: 123
}
}
在以下情境中可以获取 location 对象
在 Route component 中,以 this.props.location 获取
在 Route render 中,以 ({location}) => () 方式获取
在 Route children 中,以 ({location}) => () 方式获取
在 withRouter 中,以 this.props.location 的方式获取
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
// 已经跳转了!
}
}
可以在不同情境中使用 location:
<Link to={location} />
<NaviveLink to={location} />
<Redirect to={location />
history.push(location)
history.replace(location)
三、example
- 详情见github
- (后期添加)