react-router API

基本用法

安装命令:

$ npm install -S react-router

使用展示:

import { Router } from 'react-router';
render(<Router/>, document.getElementById('app'));

Router组件本身只是一个容器,真正的路由要通过Route组件定义。

import { Router, Route, hashHistory } from 'react-router';render((<Router history={hashHistory}><Route path="/" component={App}/></Router>
), document.getElementById('app'));

代码解释:

  • 用户访问根路由/(比如http://www.example.com/),组件APP就会加载到document.getElementById('app')。

  • Router组件有一个参数history,它的值hashHistory表示,路由的切换由URL的hash变化决定,即URL的#部分发生变化。举例来说,用户访问http://www.example.com/,实际会看到的是http://www.example.com/#/

嵌套路由

Route组件定义了URL路径与组件的对应关系。你可以同时使用多个Route组件。

<Router history={hashHistory}><Route path="/" component={App}/><Route path="/repos" component={Repos}/><Route path="/about" component={About}/>
</Router>

上面代码中,用户访问/repos时,会先加载App组件,然后在它的内部再加载Repos组件。

<App><Repos/>
</App>

App组件要写成下面的样子。

export default React.createClass({render() {return <div>{this.props.children}</div>}
})

上面代码中,App组件的this.props.children属性就是子组件。

子路由也可以不写在Router组件里面,单独传入Router组件的routes属性。

let routes = <Route path="/" component={App}><Route path="/repos" component={Repos}/><Route path="/about" component={About}/>
</Route>;<Router routes={routes} history={browserHistory}/>

path属性

Route组件的path属性指定路由的匹配规则。这个属性是可以省略的,这样的话,不管路径是否匹配,总是会加载指定组件。

<Route path="inbox" component={Inbox}><Route path="messages/:id" component={Message} />
</Route>

上面代码中,当用户访问/inbox/messages/:id时,会加载下面的组件。

如果省略外层Routepath参数,写成下面的样子。

<Route component={Inbox}><Route path="inbox/messages/:id" component={Message} />
</Route>

通配符

<Route path="/hello/:name">
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/hello(/:name)">
// 匹配 /hello
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/files/*.*">
// 匹配 /files/hello.jpg
// 匹配 /files/hello.html
<Route path="/files/*">
// 匹配 /files/
// 匹配 /files/a
// 匹配 /files/a/b

通配符规则:

  • :paramName匹配URL的一个部分,直到遇到下一个/、?、#为止。这个路径参数可以通过this.props.params.paramName取出。

  • ()表示URL的这个部分是可选的。

  • *匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。

  • **匹配任意字符,直到下一个/、?、#为止。匹配方式是贪婪模式。

常用组件

IndexRoute

上面的代码会发现访问根路径会加载不到子组件。IndexRoute就是解决这个问题,显式指定Home是根路由的子组件,即指定默认情况下加载的子组件。你可以把IndexRoute想象成某个路径的index.html。

<Router><Route path="/" component={App}><IndexRoute component={Home}/><Route path="accounts" component={Accounts}/><Route path="statements" component={Statements}/></Route>
</Router>

IndexRoute组件没有路径参数path

Redirect

<Redirect>组件用于路由的跳转,即用户访问一个路由,会自动跳转到另一个路由。

<Route path="inbox" component={Inbox}>{/* 从 /inbox/messages/:id 跳转到 /messages/:id */}<Redirect from="messages/:id" to="/messages/:id" />
</Route>

IndexRedirect

IndexRedirect组件用于访问根路由的时候,将用户重定向到某个子组件。

<Route path="/" component={App}><IndexRedirect to="/welcome" /><Route path="welcome" component={Welcome} /><Route path="about" component={About} />
</Route>

RouterContext

  • push(pathOrLoc)

    router.push('/users/12')// or with a location descriptor object
    router.push({pathname: '/users/12',query: { modal: true },state: { fromDashboard: true }
    })
  • replace(pathOrLoc)

  • go(n)

  • goBack()

  • goForward()

  • setRouteLeaveHook(route, hook)

Link

Link组件用于取代<a>元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是<a>元素的React 版本,可以接收Router的状态。

render() {return <div><ul role="nav"><li><Link to="/about">About</Link></li><li><Link to="/repos">Repos</Link></li></ul></div>
}

如果希望当前的路由与其他路由有不同样式,这时可以使用Link组件的activeStyle属性

<Link to="/about" activeStyle={{color: 'red'}}>About</Link>
<Link to="/repos" activeStyle={{color: 'red'}}>Repos</Link>

另一种做法是,使用activeClassName指定当前路由的Class

<Link to="/about" activeClassName="active">About</Link>
<Link to="/repos" activeClassName="active">Repos</Link>

IndexLink

如果链接到根路由/,不要使用Link组件,而要使用IndexLink组件。

这是因为对于根路由来说,activeStyleactiveClassName会失效,或者说总是生效,因为/会匹配任何子路由。而IndexLink组件会使用路径的精确匹配。

<IndexLink to="/" activeClassName="active">Home
</IndexLink>

另一种方法是使用Link组件的onlyActiveOnIndex属性,也能达到同样效果。

<Link to="/" activeClassName="active" onlyActiveOnIndex={true}>Home
</Link>

实际上,IndexLink就是对Link组件的onlyActiveOnIndex属性的包装。

history

Router组件的history属性,用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配。

  • hashHistory

    • 如果设为hashHistory,路由将通过URL的hash部分(#)切换,URL的形式类似example.com/#/some/path。

  • browserHistory

    • 如果设为browserHistory,浏览器的路由就不再通过Hash完成了,而显示正常的路径example.com/some/path,背后调用的是浏览器的History API

    • 种情况需要对服务器改造。否则用户直接向服务器请求某个子路由,会显示网页找不到的404错误。

  • createMemoryHistory

    • createMemoryHistory主要用于服务器渲染。它创建一个内存中的history对象,不与浏览器URL互动。

    const history = createMemoryHistory(location)
  • useRouterHistory(createHistory)

import createHashHistory from 'history/lib/createHashHistory'
const history = useRouterHistory(createHashHistory)({ queryKey: false })

表单处理

Link组件用于正常的用户点击跳转,但是有时还需要表单跳转、点击按钮跳转等操作。这些情况怎么跟React Router对接呢?

<form onSubmit={this.handleSubmit}><input type="text" placeholder="userName"/><input type="text" placeholder="repo"/><button type="submit">Go</button>
</form>

第一种方法是使用browserHistory.push

import { browserHistory } from 'react-router'// ...handleSubmit(event) {event.preventDefault()const userName = event.target.elements[0].valueconst repo = event.target.elements[1].valueconst path = `/repos/${userName}/${repo}`browserHistory.push(path)}

第二种方法是使用context对象。

export default React.createClass({// ask for `router` from contextcontextTypes: {router: React.PropTypes.object},handleSubmit(event) {// ...this.context.router.push(path)},
})

常见配置方案

React.render((<Router><Route path="/" component={App}><Route path="about" component={About} /><Route path="inbox" component={Inbox}><Route path="messages/:id" component={Message} /></Route></Route></Router>
), document.body)

| URL | 组件|
| ------| ------ |
| / | APP |
| /about | App -> About |
| /inbox | App -> Inbox |
| /inbox/messages/:id | App -> Inbox -> Message |

添加首页

React.render((<Router><Route path="/" component={App}>{/* 当 url 为/时渲染 Dashboard */}<IndexRoute component={Dashboard} /><Route path="about" component={About} /><Route path="inbox" component={Inbox}><Route path="messages/:id" component={Message} /></Route></Route></Router>
), document.body)
URL 组件
/ App -> Dashboard
/about App -> About
/inbox App -> Inbox
/inbox/messages/:id App -> Inbox -> Message

让 UI 从 URL 中解耦出来

React.render((<Router><Route path="/" component={App}><IndexRoute component={Dashboard} /><Route path="about" component={About} /><Route path="inbox" component={Inbox}>{/* 使用 /messages/:id 替换 messages/:id */}<Route path="/messages/:id" component={Message} /></Route></Route></Router>
), document.body)
URL 组件
/ App -> Dashboard
/about App -> About
/inbox App -> Inbox
/messages/:id App -> Inbox -> Message

兼容旧的 URL

现在任何人访问 /inbox/messages/5 都会看到一个错误页面。

import { Redirect } from 'react-router'React.render((<Router><Route path="/" component={App}><IndexRoute component={Dashboard} /><Route path="about" component={About} /><Route path="inbox" component={Inbox}><Route path="/messages/:id" component={Message} />{/* 跳转 /inbox/messages/:id 到 /messages/:id */}<Redirect from="messages/:id" to="/messages/:id" /></Route></Route></Router>
), document.body)

替换的配置方式

const routeConfig = [{ path: '/',component: App,indexRoute: { component: Dashboard },childRoutes: [{ path: 'about', component: About },{ path: 'inbox',component: Inbox,childRoutes: [{ path: '/messages/:id', component: Message },{ path: 'messages/:id',onEnter: function (nextState, replaceState) {replaceState(null, '/messages/' + nextState.params.id)}}]}]}
]React.render(<Router routes={routeConfig} />, document.body)

转载自react router使用教程

react-router使用总结相关推荐

  1. React router 的 Route 中 component 和 render 属性理解

    React router 的 Route 中 component 和 render 属性理解 Route 标签的三个互斥属性 render.component.children Route 就是用来匹 ...

  2. router路由react_使用React Router在React中受保护的路由

    router路由react In this video, you will see how to create a protected route using React Router. This r ...

  3. hitchhiker部署_Hitchhiker的React Router v4指南:无限远的递归路径!

    hitchhiker部署 Welcome to the third part of the Hitchhiker's Guide to React Router v4. In this article ...

  4. [React Router v4] Intercept Route Changes

    If a user has entered some input, or the current Route is in a "dirty" state and we want t ...

  5. 使用React Router以编程方式导航

    通过react-router我可以使用Link元素来创建由react路由器本地处理的链接. 我在内部看到它调用this.context.transitionTo(...) . 我想从下拉列表中进行导航 ...

  6. 从 React Router 谈谈路由的那些事

    React Router 是专为 React 设计的路由解决方案,在使用 React 来开发 SPA (单页应用)项目时,都会需要路由功能,而 React Router 应该是目前使用率最高的. Re ...

  7. [React Router v4] Conditionally Render a Route with the Switch Component

    We often want to render a Route conditionally within our application. In React Router v4, the Route ...

  8. 初探 React Router 4.0

    React Router 4.0 (以下简称 RR4) 已经正式发布,它遵循React的设计理念,即万物皆组件.所以 RR4 只是一堆 提供了导航功能的组件(还有若干对象和方法),具有声明式(引入即用 ...

  9. React Router 使用教程

    真正学会 React 是一个漫长的过程. 你会发现,它不是一个库,也不是一个框架,而是一个庞大的体系.想要发挥它的威力,整个技术栈都要配合它改造.你要学习一整套解决方案,从后端到前端,都是全新的做法. ...

  10. hitchhiker部署_《 Hitchhiker的React Router v4指南》:路由配置的隐藏值

    hitchhiker部署 Welcome to the Hitchhiker's Guide to React Router v4, Part IV! 欢迎来到< React Router v4 ...

最新文章

  1. windows 注册表讲解
  2. 模拟互联网中的dns服务布置(bind)
  3. yum使用、单用户模式、救援模式
  4. ERP笔记2-善用SVN对系统环境进行配置和组织
  5. 软工作业2:硬币游戏——代码的分析与改进
  6. 2018 NLP圣经《自然语言处理综述》最新手稿已经发布!
  7. 2015.12.11-2015.12.13 金华旅程的学习计划
  8. 计算机狐狸标志的程序,小狐狸等分线计算工具
  9. mysql英文介绍_每日科技英文48: MySQL C API简介
  10. vue router 常用操作 重定向 redirect
  11. MySQL关闭Enterprise Server源码
  12. 老板要做DDD改造,我现在慌得一比!
  13. Elasticsearch 嵌套类型nested
  14. Spark 机器学习拾遗
  15. nginx 作为Web缓存服务器
  16. python装饰器理解_Python装饰器理解(新手)
  17. mybatis 中的![CDATA[ ]]
  18. 16. Element contentEditable 属性
  19. 联想服务器万全T260G3系统,联想万全T260G3服务器电子教室更易管理
  20. Ubuntu垃圾箱目录及清空

热门文章

  1. Codeforces D546:Soldier and Number Game
  2. Linux下PHP5.5编译参数详解
  3. 百度Hi 2.3 Beta1 增量升级至内部版本号 2.3.10.12
  4. 解决电脑各种 dll 文件丢失问题
  5. 数据库JDBC的基本内容
  6. C#获取二维数组的行数和列数及其多维。。。
  7. 数据库主体在该数据库中拥有架构,无法删除解决方法(转)
  8. 怎样对齐文体框和图像按钮
  9. 互联网大厂跳槽鄙视链
  10. 趁老王不在,和隔壁邻居斗斗地主,比比大小