React Route
有幸你能看来我的这篇文章,这篇文章是继React后面写的Reactroute,所以你需要看看我前面整理的React笔记再来看Reactroute可能更容易
All the work we’ve done so far has either been in index.js or Detail.js, but now we’re going to add a third file called List.js that will render a home page for our app. From there, users will be able to select a GitHub repository, and doing so will show Detail.js as before.
So, we’ll go from having just one page listing all the React commits, forks and pulls on GitHub, to having a homepage first where users can select React, React Native, Jest, or other Facebook projects of our choosing. This involves a fairly big change, so we’re going to do this in two parts: first implement React Router in a way that preserves the exact behavior we have right now, then second add the new home page.
If you were wondering, React Router is a component that loads different pages depending on the URL your user asked for. So if the user goes tohttp://localhost:8080/helloit would serve one page, and http://localhost:8080/world would serve a different page.
Well, that’s not strictly true. To avoid having to add a server configuration, the pages React Router serves up will all start with/#/, e.g. http://localhost:8080/#/hello. This means thatindex.htmlwill automaticallybeusedtorenderallpages,whichinturnmeansthatReactRouterwillbeabletoload the right page.
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute } from 'react-router';
import createHistory from 'histroy/lib/createHistory'; import Detail from '.page/Detail'; ReactDOM.render(
<Router> //<Router history={creatHistory({ queryKey: false})}
<Route path="/" compent={ Detail } /> // onUpdate={() => window.sorollTo(0,0)}>//is right
</Router>,
document.getElementById('app')
);//is wrong
/剖析Router,Route The first import brings three components, of which we’ll be using two immediately and the other shortly. Router is React Router itself, which takes a listofURLs and React components and puts the two together. Route is one individual URL mapping, e.g. the URL detail and our Detail component. IndexRoute is used as a default route; we’ll get onto that soon.
How to Add a New Route to React Router
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute } from 'react-router';
import createHistory from 'histroy/lib/createHistory'; import Detail from '.page/Detail';
import List from './pages/List'; ReactDOM.render(
<Router history = { createHistory({ queryKey: false })}
onUpdate = {() => window.scrollTo(0, 0)}>
<Route path = "/" compent = {List} />
<Route path="/react" compent={ Detail } />
</Router>,
document.getElementById('app')
);
Creating a Link Between Pages in React Router
src/pages/List
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute } from 'react-router';
import createHistory from 'histroy/lib/createHistory';
import { Link } from 'react-router' import Detail from '.page/Detail';
import List from './pages/List'; class List extends React.Compent {
render() (
<div>
<p>Please choose a repository from the list below.</p>
<ul>
<li><link to = "/detail/react"> React</Link></li> </ul>
</div>
);
}
export default List;
Making Custom URLs with React Router Params
使用React Router里自定义的URLs参数
We currently have these two routes defined in index.js:
<Route path = "/" compent = {List} /> <Route pate = "/react" compent = { Detail } />
now
src/index.js
1 <Route path="/" component={ List } />
2 <Route path="/detail/:repo" component={ Detail } />
//代替了
<Route path="/" component={ List } />
<Route path="/react" component={ Detail } />
<Route path="/react-native" component={ Detail } />
<Route path="/jest" component={ Detail } />
:repo in the URL, React Router will automatically pull out whatever text comes in that part of the URL, then pass it to the Detail component to acton. Sure, we still need to actually do something with the repository name, but it means the Detail component will now work for /detail/react, /detail/react-native and so on.
src/pages/Detail.js
ajax.get(`https://api.github.com/repos/facebook/react/${type}`)
//上面的代码由下面的代码取代
1const baseURL = 'https://api.github.com/repos/facebook';
2 ajax.get(`${baseURL}/${this.props.params.repo}/${type}`)
Ifyouremember,thatusesES6stringinterpolationsothattheURLgetswrittenas…/react/commits, …/react/pulls, etc. Thanks to the magic of React Router, we can use the exact same technique with thenameoftherepositorytoo.Weused:repo inside our route, and React Router will automatically make that available to the Detail component as this.props.params.repo.
src/pages/List.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute } from 'react-router';
import createHistory from 'histroy/lib/createHistory';
import { Link } from 'react-router' import Detail from '.page/Detail';
import List from './pages/List'; class List extends React.Compent {
render() (
<div>
<p>Please choose a repository from the list below.</p>
<ul>
<li><link to = "/detail/react"> React</Link></li>
<li><link to = "/detail/react-native"> React-Native</Link></li>
<li><Link to = "/detail/jest">Jest</Link></li>
</ul>
</div>
);
}
Adding a Root Route Using React Router and Index Route
Let’s get started now: create a new file in the src/pages directory, and call it App.js. We’ll use this to show some basic branding for our web app, then show all the content from our child page below. Please give the new file this content:
src/pages/App.js
import React from 'react'; class App extends React.Compent {
render() {
return (
<div>
<h1>Unofficial GitHub Browser v0.1</h1>
{ this.props.children}
</div>
);
}
} export default App;
The only really interesting part of that code is {this.props.children}. All it means is “render my child components here,” so all this new App component does is add a heading above whatever page component is rendered beneath it – i.e., our List and Detail components.
The page itself was simple enough, but now we need to update our index.js file, and this is a little trickier because you need to learn two new concepts:
• Any route can have child routes inside it, and these build upon the parent route.
• If you want a child route to be used as the default when no other child matches, you use a special route called <IndexRoute>.
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRoute } from 'react-router';
import createHistory from 'history/lib/createHashHistory'; import App from './pages/App';
import List from './pages/List';
import Detail from './pages/Detail'; ReactDOM.render(
<Router history = {createHistory({ queryKey: false })}
onUpdate = {() => window.scrollTo(0,0)}>
<Route path = "/" compent = { App }>
<IndexRoute compent = { List } />
<Route path = "detail/:repo" compent = { Detail } />
</Route>
</Router>,
document.getElementById('app')
);
That’s the React Router structure for those two new concepts I just introduced. First, notice the new <IndexRoute> component: it means “if my parent route was matched but none of my siblings matched, render me.” Second, notice how <Route path="/" component={ App }> actually contains two things inside it: the IndexRoute and another Route.
The <IndexRoute> is important, and to explain what it does let’s pretend it isn’t there. If the user navigatestohttp://localhost:8080/,itwouldmatchtheApproute(path=”/”),butitwouldn’tmatch the Detail route (path=”detail/:repo”), so all they would see is “Unofficial GitHub Browser v0.1” in large text.
Cleaning up Our Routes and Preparing for the Next Step
src/routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router'; import App from './pages/App';
import List from './pages/List';
import Detail from './pages/Detail'; const routes = (
<Route path = "/" compent = { App }>
<IndexRoute compent = { List } />
<Route path = "detail/:repo" compent = { Detail } />
</Route>
); export default routes;
src/index.js
1import React from 'react';
import ReactDOM from 'react-dom';
import { Router} from 'react-router';
import createHistory from 'history/lib/createHashHistory'; import routes from './routes'; ReactDOM.render(
<Router history = {createHistory({ queryKey: false })}
onUpdate = {() => window.scrollTo(0,0)}>
{routes}
</Router>,
document.getElementById('app')
);
React Route的更多相关文章
- react -Route exact Redirect
exact是Route下的一个属性,react路由会匹配到所有能匹配到的路由组件,exact能够使得路由的匹配更严格一些(exact的值为bool型). <Route path='/' c ...
- react route使用HashRouter和BrowserRouter的区别-Content Security Policy img-src 404(Not found)
踩坑经历 昨天看了篇关于react-route的文章,说BrowserRouter比HashRouter好一些,react也是推荐使用BrowserRouter,毕竟自己在前端方面来说,就是个小白,别 ...
- React和Backbone优缺点
1.React 使用了VDOM,方便移植至其他平台,如Android等:Backbone更灵活,且与Jquery结合比较好. 2.React如果不与Jsx结合易读性很差;Backbone有强大的模板功 ...
- React 同构
React 同构 搬运 https://segmentfault.com/a/1190000004671209 究竟什么是同构呢? 同构就是希望前端 后端都使用同一套逻辑 同一套代码 Nodejs出现 ...
- React入门---基础知识-大纲-1
-----------------在慕课网学习react入门笔记-------------- ---------博主边学边记录,手把手进行学习及记录---------- --------------- ...
- BrowserRouter和HashRouter的区别
BrowserRouter: 原理是H5的history API,IE9及以下不兼容,需要由web server支持,在web client这边window.location.pathname被rea ...
- Axure 蚂蚁设计团队组件库 让交互稿美美"搭"
Github资源:https://github.com/ant-design/ant-design-pro English | 简体中文 技术实践篇 https://pro.ant.design/do ...
- 30分钟 带你浅入requirejs源码
因为最近项目想现实一个单页功能,用的是react ,然后看了一下react route,挖槽 gzip后16k? 然后我简单写了一个纯单页(不支持多页的单页,所有入口都经过rewrite跑到index ...
- [React] React Router: Route Parameters
A router library is no good if we have to hardcode every single route in our application. In this le ...
随机推荐
- 字符转十六进制 String => HEX using "hexdump" on linux
hexdump 是一款非常简单的有效的将别的形式的文档转换成十六进制的工具. 最详细的使用说明都在 man hexdump 里面,请自行查阅. 这里我摘出几个常用的例子,一目了然: 这里我做了一个实验 ...
- 挖一下插件v1.5版本发布
Chrome图片下载插件,支持网页截屏 v.1.5更新说明: 1.增加下载图片按日期分类保存选项,便于管理,用户可根据需要开启/关闭此设置 2.增加网页图片采集快捷键: (1)采集页面图片(Ctrl+ ...
- JBoss + EJB3 + MySql : 开发第一个EJB
JBoss开发Bean并不困难,而对于不知道的人来说,数据库配置才是比较棘手的问题.现在我们就来一步一步开发一个EJB3 + MySql的Bean. 一.MySql数据库的配置 1. 配置数据源 在 ...
- jvm工具
jvm工具 知识,经验是基础,数据是依据,工具是运营知识处理数据的手段 数据:运行日志.异常堆栈.GC日志.线程快照.堆转存储快照 JPS:虚拟机进程状况工具 jvm process status t ...
- 对 Select 的各种操作(JQuery)
在写表单时,经常要用到select元素,这个元素相较于其他文本框标签而言有不同.最近在写一个页面表单时需要对select进行各种操作,现将其用法收集并总结如下: HTML元素: <select ...
- C语言之函数的介绍
函数的介绍 遇到的问题: 1.代码看起来特别多,不简洁 2.修改起来非常麻烦,需要所有用到的地方都修改 函数就可以解决上述这两个问题 函数可以理解为一个打包带,就是把一段代码打包起来,用到的时候只要写 ...
- 【翻译】在Mac上使用VSCode创建你的第一个Asp.Net Core应用
Setting Up Your Development Environment 设置你的开发环境 To setup your development machine download and inst ...
- Linux学习笔记(一):常用命令(2)
3.帮助命令 A,帮助命令:man B,其他帮助命令 3.1,格式:man [命令名] 查看命令拥有哪个级别的帮助: ...
- CodeForces 384C Milking cows
水题. 对于两个$0$,肯定是先删去后面的$0$,再删去前面的$0$. 对于两个$1$,肯定是先删去前面的$1$,再删去后面的$1$. 对于一个$0$和一个$1$,无论先删哪一个,对答案做出的贡献都是 ...
- grunt--自常用配置文件--js/样式压缩打包,sass工具整合使用
// Project configuration. module.exports = function(grunt) { // 使用严格模式 'use strict'; // 这里定义我们需要的任务 ...