美文网首页
了解一下React Router V4

了解一下React Router V4

作者: LYF闲闲闲闲 | 来源:发表于2017-08-22 14:19 被阅读138次

新的React Router 从 React 汲取了很多思想和理念,它所提供的路由都可以看成是一个组件

本次升级的主要变更有:

  • 声明式 Declarative
  • 可组合 Composability

React Router V4 基于 Lerna 管理多个 Repository。在此代码库包括:

react-router: React Router 核心
react-router-dom: 用于 DOM 绑定的 React Router
react-router-native: 用于 React Native 的 React Router
react-router-redux: React Router 和 Redux 的集成
react-router-config: 静态路由配置帮助助手

在代码中该引用哪一个

上面有那么多个,我们应该在代码中引入哪一个?
在代码中我们引入react-router-dom即可,因为react-router-domreact-router多了<BrowserRouter>,<HashRouter>,<Link>,<NavLink>等一些DOM 类组件,直接引入这个比较方便使用。

新的react-router和以前的用法有什么区别

<Router>

Router是所有路由组件共用的底层接口,一般我们的应用并不会使用这个接口,而是使用高级的路由:
<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>

以前的用法可以在<Router>中使用多个<Route>,如下所示:

render((
  <Router>
    <Route path="/" component={App}/>
    <Route path="/repos" component={Repos}/>
    <Route path="/about" component={About}/>
  </Router>
), document.getElementById('app'))

但在最新的版本中,会出如下的错误:


<Router>组件下只允许存在一个子元素,将多个<Route>包裹在<div>标签里,修改如下:
render((
    <Router>
        <div>
          <Route path="/" component={App}/>
          <Route path="/repos" component={Repos}/>
          <Route path="/about" component={About}/>
        </div>
    </Router>
), document.getElementById('app'))
<Router>的引入方式

下面的三种方式都可以;

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

<Route>

Route组件主要的作用就是当匹配路由的path时,渲染某些UI。

有3种方法来渲染内容·:

  • < Route component>
    只有在地址匹配的时候React的组件才会被渲染,路由会根据指定的组件使用React.createElement来创建一个新的React element
    <Route path="/user/:username" component={User}/>
     const User = ({ match }) => {
    return <h1>Hello {match.params.username}!</h1>
    }
    
  • < Route render>
    使用render属性,你可以选择传一个在地址匹配时被调用的函数,而不会新创建一个像component一样的React element
    <Route exact path="/topics" render={() => (
         <h3>Please select a topic.</h3>
    )}/>
    
  • < Route children>
    有时候你可能想不管地址是否匹配都渲染一些内容,这种情况你可以使用children属性。它与render属性的工作方式基本一样。
     <Route path="aaa" children={() => (
         <h3>hello children</h3>
     )}/>
    

这三种渲染方法都会获得相同的三个的属性:

  • match
    match 对象包含了 <Route path> 如何与URL匹配的信息。match 对象包含以下属性:
    • params -( object 类型)即路径参数,通过解析URL中动态的部分获得的键值对。
    • isExact - 当为 true 时,整个URL都需要匹配。
    • path -( string 类型)用来做匹配的路径格式。在需要嵌套 <Route> 的时候用到。
    • url -( string 类型)URL匹配的部分,在需要嵌套 <Link> 的时候会用到。
  • location
    Location 是指你当前的位置,下一步打算去的位置,或是你之前所在的位置
  • history

一个例子

更多的用法,待续......

参考
https://github.com/react-translate-team/react-router-CN
初探 React Router 4.0
http://www.jianshu.com/p/e3adc9b5f75c
React Router V4 系列专栏(一)
https://github.com/iuap-design/blog/issues/176
React Router v4 入坑指南
http://www.codezhan.com/Front-end/2017/0707/8293.html
http://www.jianshu.com/p/27ee7df4ccc1

相关文章

网友评论

      本文标题:了解一下React Router V4

      本文链接:https://www.haomeiwen.com/subject/defkrxtx.html