React-router 初学者的14个lessons

Lesson1
1、首先确保安装了Node.js和npm依赖包管理工具
2、在git上克隆官方示例程序

git clone https://github.com/reactjs/react-router-tutorial

cd react-router-tutorial

cd lessons/01-setting-up

npm install

npm start

运行完成后打开:http://localhost:8080
就可以在浏览器看见: "Hello React Router"
打开modules/App.js,更改里面内容,可以看到浏览器上的内容随时变化!

Lesson2 : rendering a router
1、打开index.js
首先import Router、Route和hashHistory,然后render Reouter替换原来的App组件。这是由于:React Router 是一个组件。Router 本身是一个容器,真正的路由都要由Route去定义。
// ...

import { Router, Route, hashHistory } from 'react-router'

render(( <Router history={hashHistory}>

<Route path="/" component={App}/>

</Router>), document.getElementById('app'))

上面访问的路由为“/”,组件是App。路由的切换由URL得hash变化决定,即URL的#部分发生变化。
2、添加Scene
.modules/About.js
.modules/Repos.js
// modules/About.js

import React from 'react'export

default React.createClass({ render() { return <div>About</div> }})

// modules/Repos.js

import React from 'react'export

default React.createClass({ render() { return <div>Repos</div> }})

把场景添加到路由里面
// insert into index.js

import About from './modules/About'

import Repos from './modules/Repos'

render(( <Router history={hashHistory}>

<Route path="/" component={App}/>

{/* add the routes here */}

<Route path="/repos" component={Repos}/>

<Route path="/about" component={About}/>

</Router>), document.getElementById('app'))

现在访问: http://localhost:8080/#/abouthttp://localhost:8080/#/repos

Lesson3 Navigating with Link
Link类似于之前用过的<a/>标签
// modules/App.js

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

export default React.createClass({

render() {

return ( <div>

<h1>React Router Tutorial</h1>

<ul role="nav">

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

<li><Link to="/repos">Repos</Link></li>

</ul>

</div> ) }})

访问:http://localhost:8080

lesson4 嵌套的路由
这个功能可以做出类似Nav的功能,Route里面可以嵌套多个Route
// index.js// ...

render((

<Router history={hashHistory}>

<Route path="/" component={App}>

{/* make them children of App */}

<Route path="/repos" component={Repos}/>

<Route path="/about" component={About}/>

</Route>

</Router>), document.getElementById('app'))

在App里面
// modules/App.js// ...

render() {

return (

<div>

<h1>React Router Tutorial</h1>

<ul role="nav">

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

<li><Link to="/repos">Repos</Link></li>

</ul>

{/* add this */}

{this.props.children}

</div>

) }

则UI结构如下:
<App>
<About/>
</App>
<App>
<Repos/>
</App>

Lesson 5 Active Links
通过行内样式表改变Link的样式:
// modules/App.js

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

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

也可以添加className在css文件中设置样式
// modules/App.js

<li><Link to="/about" activeClassName="active">About</Link></li>

<li><Link to="/repos" activeClassName="active">Repos</Link></li>

创建css文件,并在index.html中引入
// index.html
<link rel="stylesheet" href="index.css" />
我们不用为每个Link都添加activeClassName,这里我们使用一个spread operator
创建modules/NavLink.js
// modules/NavLink.js

import React from 'react'

import { Link } from 'react-router'

export default React.createClass({

render() {

return <Link {...this.props} activeClassName="active"/>

}

})

在modules/App.js中这样写:
// modules/App.js

import NavLink from './NavLink'

<li><NavLink to="/about">About</NavLink></li>

<li><NavLink to="/repos">Repos</NavLink></li>

Lesson 6 URL Params
1、添加一个带参数的路由
建立一个文件:modules/Repo.js
// modules/Repo.js

import React from 'react'

export default React.createClass({

render() {

return (

<div> <h2>{this.props.params.repoName}</h2> </div>

)

}})

2、在index.js里面添加新路由
// import Repo

import Repo from './modules/Repo'

render((

<Router history={hashHistory}>

<Route path="/" component={App}>

<Route path="/repos" component={Repos}/>

{/* add the new route */}

<Route path="/repos/:userName/:repoName" component={Repo}/>

<Route path="/about" component={About}/>

</Route>

</Router>), document.getElementById('app'))

3、在Repo.js里面添加跳转的Link
// Repos.js

import { Link } from 'react-router'

export default React.createClass({

render() {

return (

<div>

<h2>Repos</h2>

{/* add some links */}

<ul>

<li><Link to="/repos/reactjs/react-router">React Router</Link></li>

<li><Link to="/repos/facebook/react">React</Link></li>

</ul>

</div> )

}})

附:path属性可以匹配通配符
<Route path="/hello/:name">
:paramName 匹配URL的一个部分,知道遇到下一个/、?、#为止。路径参数可以通过this.props.params.paramName获取
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/hello(/:name)">
()表示URL的这个部分是可选的
// /hello
// /hello/micale
// /hello/ryan
<Route path="/files/.">
匹配任意字符直到下一个字符为止,非贪婪模式
// /files/hello.jpg
// /files/hello.html
<Route path="/files/
">
// /files/
// /files/a
// /files/a/b
<Route path="/*/.jpg">
**匹配任意字符,直到遇到下一个/、?、#为止,贪婪模式
// /files/hello.jpg
// /files/path/to/file.jpg

路由匹配规则是从上到下执行,一旦发现匹配,就不再匹配其余的规则了。

Lesson 7 更多的嵌套
1、将Repo的路由放进Repos的路由
//index.js

<Route path="/repos" component={Repos}>

<Route path="/repos/:userName/:repoName" component={Repo}/>

</Route>

//Repos.js

<div>

<h2>Repos</h2>

<ul>

<li><Link to="/repos/reactjs/react-router">React Router</Link></li>

<li><Link to="/repos/facebook/react">React</Link></li>

</ul>

{/* will render Repo.js when at /repos/:userName/:repoName */} #{this.props.children}

</div>

2、添加NavLink
// modules/Repos.js
import NavLink from './NavLink'

<li><NavLink to="/repos/reactjs/react-router">React Router</NavLink></li>

<li><NavLink to="/repos/facebook/react">React</NavLink></li>

Lesson 8 Index Routes
当我们访问/在app里出现了一个空白,我们想让他渲染一个Home的component
IndexRoute显示指定Home是根路由的子组件,即指定默认情况下加载的子组件。IndexRoute组件没有路径参数path
//modules/Home.js

import React from 'react'

export default React.createClass({

render() {

return <div>Home</div>

}

})

在App里如果没有任何场景被渲染的时候,就渲染Home
// modules/App.js

import Home from './Home'

<div>

{/* ... */}

{this.props.children || <Home/>}

</div>

添加IndexRoute
// index.js

import { Router, Route, hashHistory, IndexRoute } from 'react-router'

import Home from './modules/Home'

render((

<Router history={hashHistory}>

<Route path="/" component={App}>

{/* add it here, as a child of / */}

<IndexRoute component={Home}/>

<Route path="/repos" component={Repos}>

<Route path="/repos/:userName/:repoName" component={Repo}/>

</Route>

<Route path="/about" component={About}/>

</Route>

</Router>), document.getElementById('app'))

IndexRoute没有path ,

Lesson 9 Index Links
添加可以返回Home的方法,IndexLink
//App.js

import { IndexLink } from 'react-router'

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

使用onlyActiveOnIndex Property

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

<li><NavLink to="/" onlyActiveOnIndex={true}>Home</NavLink></li>

Lesson 10 Clean URLs with Browser History
配置浏览器历史
//index.js
// bring in browserHistory instead of hashHistory

import { Router, Route, browserHistory, IndexRoute } from 'react-router'

render((

<Router history={browserHistory}>

{/* ... */}

</Router>

), document.getElementById('app'))

点击链接,然后刷新,会得到

Cannot GET /repos

这是因为服务器端配置的原因,目前的服务器不知道如何处理URL
在package.json中添加:

"start": "webpack-dev-server --inline --content-base . --history-api-fallback"

同时要将我们的文件引用,相对路径为绝对路径
//index.html

<link rel="stylesheet" href="/index.css">

<script src="/bundle.js"></script>

重启服务器:npm start

Lesson 11 Production-ish Server
Webpack dev server 不是生产模式的服务器,下面配置生产模式下的服务器
安装依赖模块:

npm install express if-env compression --save

更新package.json

"scripts": {

"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",

"start:dev": "webpack-dev-server --inline --content-base . --history-api-fallback",

"start:prod": "webpack && node server.js"

},

此时的脚本说明,如果运行npm start 启动服务器,如果在生产环境下执行start:prod,如果不是,执行start:dev
在根目录下创建server.js
//server.js

var express = require('express')

var path = require('path')

var compression = require('compression')

var app = express()

// serve our static stuff like index.css

app.use(express.static(__dirname))

// send all requests to index.html so browserHistory in React Router works

app.get('*', function (req, res) {

res.sendFile(path.join(__dirname, 'index.html'))

})

var PORT = process.env.PORT || 8080

app.listen(PORT, function() {

console.log('Production Express server running at localhost:' + PORT)

})

现在运行:NODE_ENV=production npm start
现在就有了生产环境下的app
此时运行:http://localhost:8080/package.json就可以获得json文件的内容,让我们重新更新文件的路径来解决这个问题
创建一个public的文件夹,并且把index.html 和 index.css文件放进去
1、更新server.js指向正确的路径:
// server.js

app.use(express.static(path.join(__dirname, 'public')))

app.get('*', function (req, res) {

res.sendFile(path.join(__dirname, 'public', 'index.html'))

})

2、更新webpack编译时的输出路径
// webpack.config.js

output: {

path: 'public',

}

3、在服务器启动脚本中,添加该路径

"start:dev": "webpack-dev-server --inline --content-base public --history-api-fallback",

4、添加一些代码
// webpack.config.js

var webpack = require('webpack')

module.exports = {

//...

plugins: process.env.NODE_ENV === 'production' ? [ new #webpack.optimize.DedupePlugin(), new #webpack.optimize.OccurrenceOrderPlugin(), new #webpack.optimize.UglifyJsPlugin() ] : [],

//...

}

在express中添加conpression
// server.js

var compression = require('compression')

var app = express()

// must be first!

app.use(compression())

现在我们可以在生产模式下启动服务器了
NODE_ENV=production npm start

Lesson 12 Navigating Programatically
之前使用的都是Link进行路由的跳转,而实际使用更多的使用表单提交,按钮点击来进行路由的切换
在Repos创建一个表单提交
// modules/Repos.js

Paste_Image.png

那么可以使用以下方式保存路由

Paste_Image.png

Lesson 13 服务器端渲染
Lesson 14 结束语

附:组件介绍
1、Redirect组件:<Redirect>用于路由的跳转,即访问一个路由,就会自动跳转到另一个路由.
<Route path="inbox" component={Inbox}>
{/* 从 /inbox/messages/:id 跳转到 /messages/:id */}
<Redirect from="messages/:id" to="/messages/:id" />
</Route>
访问/inbox/message/5,会自动跳到/messages/5
2、IndexRedirect 组件
访问根路由的时候,将用户重定向到某个子组件。
3、Link 组件取代<a>标签,
4、IndexLink 如果连接到根路由不要使用Link要使用IndexLink(使用路由的精确匹配)
5、history属性
Router的history属性监听浏览器地址的变化,并将URL解析为一个地址对象,供React Router 匹配
6、表单处理:Link组件用于正常的用户点击跳转,但有时候还需要表单跳转、点击按钮跳转。
有两种方案:1、使用browserHistory.push
2、使用context对象
7、路由的钩子
每个路由都有Enter和Leave的钩子,当用户进入或者离开该路由时触发

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

推荐阅读更多精彩内容