React-Router v4 学习

React-Router v4

1. 设计理念

React-Router v4 的核心思想是 “动态路由”,它是相对于 “静态路由” 提出的设计概念。

何为静态路由?在服务器端所有的路由都是在设计过程已经规划完成。在许多客户端框架中也遵循了上述思路,即在页面渲染之前先规划好路由,将路由导入到顶层的模块中。但这种理念在 React-Router 中不再适用,作者希望在学习 React-Router 之前放弃 “静态路由” 设计思路。

1.1. 动态路由

在 React-Router 中的所有设置都是组件,因此路由是随着应用的渲染被同时计算得到,而不是独立于应用之外。为了解释这个理念我们首先学习 React-Router 在应用中的使用,

  • 将 React-Router 的组件声明到应用顶层:

    import { BrowserRouter } from 'react-router-dom'
    
    ReactDOM.render((
      <BrowserRouter>
        <App/>
      </BrowserRouter>
    ), el)
    
  • 使用 link 组件指向相应的位置:

    const App = () => (
      <div>
        <nav>
          <Link to="/dashboard">Dashboard</Link>
        </nav>
      </div>
    )
    
  • 最后利用 Route 组件关联位置与显示 UI:

    const App = () => (
      <div>
        <nav>
          <Link to="/dashboard">Dashboard</Link>
        </nav>
        <div>
          <Route path="/dashboard" component={Dashboard}/>
        </div>
      </div>
    )
    

如果用户访问 /dashboard , Route 组件会将路由形式的对象 {match, location, history} 作为属性参数传给<Dashboard {...props}> 组件进行渲染,否则不会渲染。

到此为止,似乎与 “静态路由” 的概念没有区别,但是不要忘记 Route 是一个组件,这就意味着 Route 组件是否渲染和其中的 pathcomponent 都可以由父组件的状态或属性进行设置。

1.2. 嵌套路由

在动态路由中配置嵌套路由就好像 div 标签中嵌套一个 div , 因为 Route 就是一个组件标签。

const App = () => (
  <BrowserRouter>
    {/* 这里是 div 标签*/}
    <div>
      {/* 这里是 Route 组件标签*/}
      <Route path="/tacos" component={Tacos}/>
    </div>
  </BrowserRouter>
)

// 当 url 匹配 /tacos 时, 该组件被渲染
const Tacos  = ({ match }) => (
  // 这是嵌套的 div 标签
  <div>
    {/* 这是嵌套的 Route 组件标签,
        match.url 用以实现相对路径 */}
    <Route
      path={match.url + '/carnitas'}
      component={Carnitas}
    />
  </div>
)

1.3. 响应式路由

利用动态路由理念很容易在 React-Native 中实现响应式的布局。

const App = () => (
  <AppLayout>
    <Route path="/invoices" component={Invoices}/>
  </AppLayout>
)

const Invoices = () => (
  <Layout>

    {/* always show the nav */}
    <InvoicesNav/>

    <Media query={PRETTY_SMALL}>
      {screenIsSmall => screenIsSmall
        // small screen has no redirect
        ? <Switch>
            <Route exact path="/invoices/dashboard" component={Dashboard}/>
            <Route path="/invoices/:id" component={Invoice}/>
          </Switch>
        // large screen does!
        : <Switch>
            <Route exact path="/invoices/dashboard" component={Dashboard}/>
            <Route path="/invoices/:id" component={Invoice}/>
            <Redirect from="/invoices" to="/invoices/dashboard"/>
          </Switch>
      }
    </Media>
  </Layout>
)

2. 快速入门

首先给出官方的基础案例:

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

// 三个基础呈现组件

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)

const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
)

// 一个内嵌的组件

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>
          Components
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic}/>
    <Route exact path={match.url} render={() => (
      <h3>Please select a topic.</h3>
    )}/>
  </div>
)

// 首页组件

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/topics">Topics</Link></li>
      </ul>

      <hr/>

      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
    </div>
  </Router>
)
export default BasicExample

随后分析上例给出的三个 React-Router 组件,分别是 <BrowserRouter><Route><Link>

2.1. <BrowserRouter>

这是一个路由管理器,使用 HTML5 的 history API (pushState, replaceState, popState) 同步访问 URL 和组件。具体声明如下:

import { BrowserRouter } from 'react-router-dom'

<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App/>
</BrowserRouter>

2.1.1. basename: string

应用的根目录,如果你的应用只是整个服务中的子服务,仅适应于某个子目录,那么就应该设置这个参数。

<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">

2.2. <Link>

该组件用以声明应用的链接(导航)

import { Link } from 'react-router-dom'

<Link to="/about">About</Link>

2.2.1. to: string || object

定义需要导航的路径。

<Link to="/courses"/>

<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { fromDashboard: true }
}}/>

2.2.2. replace: bool

如果该选项设置为 true,当你点击链接时,会在 history 栈中取代当前的状态路径而不是添加一个新状态路径。

2.3. <Route>

这是 React-Router 中最重要的组件了,当请求的状态路径与该组件给出的 path 一致时,会渲染所对应的 UI 组件。

import { BrowserRouter as Router, Route } from 'react-router-dom'

<Router>
  <div>
    <Route exact path="/" component={Home}/>
    <Route path="/news" component={NewsFeed}/>
  </div>
</Router>

在 <Route> 组件中有三种渲染方式:

  • <Route component>
  • <Route render>
  • <Route children>

每一种方式都会传入相同形式的路由属性 —— {match, location, history}

2.3.1. component

使用 component 渲染方式时,React 会自动将所对应的组件转化为 React 组件,因此如果所对应组件是内联函数形式,请使用 render 或 children 渲染方式,避免每次都生成新的 React 组件。

<Route path="/user/:username" component={User}/>

2.3.2. render: func

该方式取代了React 生成组件的过程,而是直接执行一个函数,此外还经常用于路由的打包。

// 直接执行函数
<Route path="/home" render={() => <div>Home</div>}/>

// 打包路由
const FadingRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    <FadeIn>
      <Component {...props}/>
    </FadeIn>
  )}/>
)

<FadingRoute path="/cool" component={Something}/>

2.3.3. children: func

有时无论路径是否匹配都要渲染组件,这种情况下使用 children 渲染方式,它和 render 方式类似只是多了一个匹配过程。

<ul>
  <ListItemLink to="/somewhere"/>
  <ListItemLink to="/somewhere-else"/>
</ul>

const ListItemLink = ({ to, ...rest }) => (
  <Route path={to} children={({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}/>
)

注意: component 和 render 方式都优先于 children 方式,因此无法在一个 <Route> 组件中同时使用。

2.3.4. path: string

一个符合正则的有效 URL 路径,当 Route 中没有 path 时,该路由总是匹配 。

<Route path="/users/:id" component={User}/>

2.3.5. exact: bool

完全匹配的选项。

<Route exact path="/one" component={About}/>

完全匹配的逻辑:

path location.pathname exact matches?
/one /one/two true no
/one /one/two false yes

2.4. history

<Route> 组件相关的还有三个对象,分别是 historymatchlocation。在这节中我们先来了解 history 这个可变对象。

history 是 React-Router 极少的依赖模块之一,它主要作用是在不同的环境下管理会话。经常会使用到的 history 有:

  • browser history:DOM 的具体应用,支持 HTML5 的 history API。
  • hash history:DOM 的具体应用,用以兼容老版本的浏览器。
  • memory history:在无 DOM 或测试环境下通过内存方式处理来实施,适合 React-Native。

和history 对象相关的主要属性和方法有:

  • length:history 栈中的状态路径个数。
  • action:当前的操作,字符串形式(PUSH, REPLACE, POP)
  • location:当前的状态路径。
    • pathname: URL 路径字段
    • search:URL 查询字段
    • hash:URL 的 hash 字段
    • state:路径的状态,只在 browser 和 memory history 中有效。
  • push(path, [state]):将状态路径压入 history 栈。
  • replace(path, [state]):替换当前的状态路径。
  • go(n):向前移动当前指针 n 次。
  • goBack()go(-1)
  • goForward()go(1)
  • block(prompt):暂时阻止导航(“您确定离开”)。

history 是可变的,因此状态路径的访问方式推荐使用 <Route> 的属性(props)里间接获取,而不是直接使用 history.location。这可以保证在 React 生存周期里能够获得正确的比较。

class Comp extends React.Component {
  componentWillReceiveProps(nextProps) {
    // 返回 true
    const locationChanged = nextProps.location !== this.props.location

    // 错误,总是 false,因为 history 是可变的。
    const locationChanged = nextProps.history.location !== this.props.history.location
  }
}

<Route component={Comp}/>

2.5. location

在本文中我一直称之为状态路径,意思很明显就是具有状态的路径。该对象的与 url 对应,其具体属性如下:

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere'
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}

状态路径会在以下几个位置由 React-Router 给出:

  • Route component 由 this.props.location 给出
  • Route render({location}) => () 给出
  • Route children({location}) => () 给出
  • withRouter 由 this.props.location 给出

你也可以在这几个位置定义状态路径:

  • Link to
  • Redirect to
  • history.push
  • history.replace

状态路径中的状态可用于 UI 分支的显示等情景。你也可以通过 <Route><Switch> 组件传递状态路径,这在动画显示和延迟导航中非常有用。

2.6. match

match 对象用以描述 <Route path> 匹配 URL 的结果,其实就是 <Route> 组件的 state ,<Route> 组件根据 match 对象进行状态转换,主要的属性有:

  • params:键值对对象对应正则模式中的参数字段。
  • isExact:是否完全匹配。
  • path:匹配使用的正则模式。
  • url:所匹配的 URL 路径字段。

可以在下面位置访问该对象,意味着将 <Route> 的 state 传递为子组件的 props:

  • Route component 由 this.props.match 给出
  • Route render 由 ({match}) => () 给出
  • Route children 由 ({match}) => () 给出
  • withRouter 由 this.props.match 给出

如果路由中没有 path,将匹配所有路径, match 对象就是其父对象的 match。

3. API 查漏补缺

官方教程中给出了许多实例,如果了解了上述 API 大部分代码都能看懂,还有一些 API 主要是增强使用的,为程序员在编程中提供了更多选择和便利。

3.1. <Redirect>

执行 <Redirect> 将会使应用导航到一个新的位置,同时在 history 栈中新位置替换当前位置。因为是替换操作所以在 <Redirect> 中通常会使用状态路径,并在状态路径中记录当前位置,以实现回溯路径的操作。

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

3.1.1. to: string || object

重定向的位置。

3.1.2. push: bool

该属性为 true 时,history 栈的操作不再是替换操作而是压入新的位置元素。

<Redirect push to="/somewhere/else"/>

3.1.3. from: string

表明从那个位置进行重定向操作的。该属性只有在 <Switch> 组件中才有效。实际上该属性就是 <Route> 组件中 path 属性的别称,与此同理还可以使用 exactstrictpath

<Switch>
  <Redirect from='/old-path' to='/new-path'/>
  <Route path='/new-path' component={Place}/>
</Switch>

3.2. <Switch>

组件和语法中的 switch 功能类似,执行第一个匹配的路由。这个逻辑很直观也就是排他性,主要解决使用多个 <Route> 时多个路由同时匹配的问题。

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>

如果 URL 是 /about ,那么上述三个路由都匹配,此时希望只有第一个路由渲染,就需要使用 <Switch> 组件了:

import { Switch, Route } from 'react-router'

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

3.2.1. location: object

如果 <Switch> 组件中给出了 location 属性,子元素将不再与当前位置或 URL 进行匹配操作,而是与该属性进行匹配,并且匹配的子元素的 location 值将被覆盖为 <Switch> 的 location 属性值。

3.2.2. children: node

<Switch> 组件中子元素可以是 <Route><Redirect> 组件, <Route> 使用 path 属性进行匹配,而 <Redirect> 使用 from 属性进行匹配。

<Switch>
  <Route exact path="/" component={Home}/>

  <Route path="/users" component={Users}/>
  <Redirect from="/accounts" to="/users"/>

  <Route component={NoMatch}/>
</Switch>

3.3. <NavLink>

特殊的 <Link> 组件,主要作用是实现导航栏。

activeClassName: string

当链接激活时的类名,默认是 active

activeStyle: object

链接激活时的样式。

<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: 'bold',
    color: 'red'
   }}
>FAQs</NavLink>

isActive: func

在链接匹配的基础上添加逻辑以决定是否该链接激活。

// only consider an event active if its event id is an odd number
const oddEvent = (match, location) => {
  if (!match) {
    return false
  }
  const eventID = parseInt(match.params.eventID)
  return !isNaN(eventID) && eventID % 2 === 1
}

<NavLink
  to="/events/123"
  isActive={oddEvent}
>Event 123</NavLink>

其他属性 exact, strict, location 参考 <Link>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容