React Router 4.0学习

2018-11-15  本文已影响16人  lmmy123

引用

react-router 还是 react-router-dom?
只需引用 react-router-dom 这个包就行了。当然,如果搭配 redux ,你还需要使用 react-router-redux。

组件

<BrowserRouter>

一个使用了HTML5 history API的高阶路由组件,保证你的ui界面和url保持同步
组件属性:

<BroserRouter basename='/minooo' />
<Link to='/react' />  // 渲染成 <a href="/minooo/react" /> 
const supportsHistory = 'pushState' in window.history
<BrowserRouter forceRefresh={!supportsHistory} />

-keyLength: number
作用:设置它里面路由的 location.key 的长度。默认是6。(key的作用:点击同一个链接时,每次该路由下的 location.key都会改变,可以通过 key 的变化来刷新页面。)
使用场景:按需设置。

<BrowserRouter keyLength={12} />
<HashRouter>

Hash history 不支持 location.key 和 location.state。另外由于该技术只是用来支持旧版浏览器,因此更推荐大家使用 BrowserRouter,此API不再作多余介绍。

<Route>

基本的职责就是当页面的访问地址与 Route 上的 path 匹配时,就渲染出对应的 UI 界面。
<Route> 自带三个 render method 和三个 props
render methods 分别是:

<Link>

to: string
to: Object
replace: bool

<NavLink>

是<Link>的特殊版,为页面导航准备用的

<Switch>

只渲染出第一个与当前访问地址匹配的<Route>或<Redirect>

<Switch>
  // 这里每次只匹配一个路由
  <Route />
  <Route/>
</Switch>
- children: node
<Switch> 下的子节点只能是 <Route> 或 <Redirect> 元素。只有与当前访问地址匹配的第一个子节点才会被渲染,<Route> 元素用它们的 path 属性匹配,<Redirect> 元素使用它们的 from 属性匹配。如果没有对应的 path 或 from,那么它们将匹配任何当前访问地址
<Redirect>

<Redirect> 渲染时将导航到一个新地址,这个新地址覆盖在访问历史信息里面的本该访问的那个地址。

<Prompt>

当用户离开当前页面做出一些提示

<Prompt message="确定要离开?">
<Prompt message={location => (
  `Are you sue you want to go to ${location.pathname}?` 
)} />

对象和方法

history

histoty 是 RR4 的两大重要依赖之一(另一个当然是 React 了)

const location= this.props.loaction

location
location 是指你当前的位置,将要去的位置,或是之前所在的位置
在以下情境中可以获取 location 对象

componentWillReceiveProps(nextProps) {
  if (nextProps.location !== this.props.location) {
    // 已经跳转了!
  }
}

match
match 对象包含了 <Route path> 如何与 URL 匹配的信息,具有以下属性:

当一个 Route 没有 path 时,它会匹配一切路径。


文章参考:https://www.jianshu.com/p/e3adc9b5f75c/作者:minooo

上一篇 下一篇

猜你喜欢

热点阅读