博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
React Router入门指南
阅读量:2519 次
发布时间:2019-05-11

本文共 19698 字,大约阅读时间需要 65 分钟。

by Nader Dabit

纳德·达比特(Nader Dabit)

React Router入门指南 (Beginner’s Guide to React Router)

Or what I wish I knew when starting with React Router.

还是我希望从React Router开始时所知道的。

Click to go to the Github repo

单击转到Github存储库

This tutorial uses React Router version 2.0.1 and Babel version 6.7.4
本教程使用React Router版本2.0.1和Babel版本6.7.4

React Router is the standard routing library for React. From the docs:

React Router是React的标准路由库。 从文档:

“React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.”
“ React Router使您的UI与URL保持同步。 它具有一个简单的API,具有强大的功能,例如,延迟代码加载,动态路由匹配和内置的位置转换处理。使URL成为您的首要考虑,而不是事后考虑。”

步骤1.开始 (Step 1. Getting Started)

To get started you can either and jump to step two, or follow along the next steps and set up your project manually.

要开始使用,您可以并跳至第二步,或者按照以下步骤手动设置项目。

手动设定 (Manual Setup)

First, let’s get our environment set up with React, Babel, and webpack. First create a folder and cd into it. Then run npm init -y:

首先,让我们使用React,Babel和webpack设置环境。 首先创建一个文件夹并cd进入它。 然后运行npm init -y:

npm init -y
  • -y just answers yes to all of the questions

    -y对所有问题回答是

Next, install react, react-router, and react-dom and save them as dependencies:

接下来,安装react,react-router和react-dom并将它们另存为依赖项:

npm i react react-dom react-router@2.0.1 --save

Next, install our dev dependencies. These will be webpack, webpack-dev-server, babel-core, babel-loader, babel-preset-es2015, and babel-preset-react

接下来,安装我们的开发依赖项。 这些将是webpack,webpack-dev-server,babel-core,babel-loader,babel-preset-es2015和babel-preset-react

npm i webpack webpack-dev-server babel-core babel-loader babel-preset-es2015 babel-preset-react --save-dev

Now, let’s create the configuration files for webpack and babel:

现在,让我们为webpack和babel创建配置文件:

touch .babelrc webpack.config.js

Next, let’s create a folder for our code. We’ll call this folder app:

接下来,让我们为代码创建一个文件夹。 我们将这个文件夹称为:

mkdir app

In the app directory create three files: index.html app.js main.js

在app目录中,创建三个文件:index.html app.js main.js

cd apptouch index.html app.js main.js

Our file structure should now look like this:

现在,我们的文件结构应如下所示:

Now, open the .babelrc file and add the presets for react and ES2015:

现在,打开.babelrc文件并添加react和ES2015的预设:

{ "presets": [  "es2015",  "react" ]}

In webpack.config.js, add the following configuration to get us started:

在webpack.config.js中,添加以下配置以开始使用:

module.exports = {  entry: './app/main.js',  output: {    path: './app',    filename: 'bundle.js'  },  devServer: {    inline: true,    contentBase: './app',    port: 8100  },  module: {    loaders: [      {        test: /\.js$/,        exclude: /node_modules/,        loader: 'babel'      }    ]  }}

If you would like to learn more about webpack and babel,

如果您想了解有关webpack和babel的更多信息,

Now that webpack and babel are set up. Let’s create a shortcut for webpack-dev-server. Open package.json and insert the following script in the “scripts” key:

现在已经设置了webpack和babel。 让我们为webpack-dev-server创建一个快捷方式。 打开package.json并在“ scripts”键中插入以下脚本:

"scripts": {  "start": "webpack-dev-server"}

Now, we can just run npm start to start our project.

现在,我们可以运行npm start来启动我们的项目。

Let’s now set up our HTML and React. Open index.html and create a base html page. Then, add a div with the id of root, and a script tag referencing bundle.js:

现在让我们设置HTML和React。 打开index.html并创建一个基本的html页面。 然后,添加一个ID为root的div和一个引用bundle.js的脚本标签:

        
React Router

Now, let’s go into our main.js and set up an entry point for our app. Type this into your main.js file:

现在,让我们进入main.js并为我们的应用程序设置一个入口点。 在您的main.js文件中输入以下内容:

import React from 'react'import ReactDOM from 'react-dom'import App from './app'ReactDOM.render(
, document.getElementById('root'))

Now, let’s go into app.js and create our app component. Open app.js and type the following:

现在,让我们进入app.js并创建我们的应用程序组件。 打开app.js并输入以下内容:

import React, { Component } from 'react'import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'
const App = () => 

Hello World!

export default App

We are not using Component or any of the Router / react-router components yet, but we are bringing them in so we can get started in step two.

我们尚未使用Component或任何Router / react-router组件,但我们将它们引入,以便我们可以从第二步开始。

Now, if you run the project and navigate to you should get ‘Hello World!!!!!!’ on your screen:

现在,如果您运行该项目并导航至 ,则应显示“ Hello World !!!!!!”。 在屏幕上:

npm start

步骤2.基本路由 (Step 2. Basic Routing)

Let’s set up a basic route. We will replace the App component with a React class, which will return a Router component. Router will wrap all of the routes we are going to define.

让我们建立一条基本路线。 我们将用React类替换App组件,这将返回一个Router组件。 路由器将包装我们要定义的所有路由。

Each route will be identified in a <Route> component. The <Route> component will take two properties: path and component. When a path matches the path given to the <Route> component, it will return the component specified.

每个路由将在<Route>组件中标识。 <Route>组件将具有两个属性:path和component。 当路径与给<Route>组件的路径匹配时,它将返回指定的组件。

In app.js, refactor the App component to look like this:

在app.js中,将App组件重构为如下所示:

import React, { Component } from 'react'import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router'
class App extends Component {  render() {    return (      
) }}
const Home = () => 

Hello from Home!

const Address = () =>

We are located at 555 Jackson St.

export default App

Now, if you navigate to you should see our Home component, and if you navigate to you should see our Address component.

现在,如果导航到 ,则应该看到我们的Home组件;如果导航到 ,则应该看到我们的Address组件。

You will notice that there are random strings after the hash in your address bar:

您会注意到地址栏中的哈希后面有随机字符串:

When using hash history, you’ll see an extra item in your query string that looks something like _k=123abc. This is a key that history uses to look up persistent state data in window.sessionStorage between page loads.

使用哈希历史记录时,您会在查询字符串中看到一个类似于_k = 123abc的项。 这是历史记录用来在页面加载之间在window.sessionStorage中查找持久状态数据的键。

If you would like a cleaner address, or you are using this in production, you may want to look into browserHistory vs hashHistory. When using browserHistory you must have a server that will always return your server at any route, for example if using nodejs, a configuration like the following (from the docs) would work:

如果您想要一个更简洁的地址,或者在生产中使用该地址,则可能需要研究browserHistory与hashHistory。 当使用browserHistory时,您必须拥有一台服务器,该服务器将始终以任何路线返回您的服务器,例如,如果使用nodejs,则如下所示的配置(来自docs)将起作用:

const express = require('express')const path = require('path')const port = process.env.PORT || 8080const app = express()// serve static assets normallyapp.use(express.static(__dirname + '/public'))// handle every other route with index.html, which will contain// a script tag to your application's JavaScript file(s).app.get('*', function (request, response){  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))})app.listen(port)console.log("server started on port " + port)

To learn more about browserHistory, check out

要了解有关browserHistory的更多信息,请查看

For the rest of this tutorial, we will be using hashHistory.

在本教程的其余部分中,我们将使用hashHistory。

步骤3. 404路线 (Step 3. 404 route)

Now, what happens if we hit a route that is not defined? Let’s set up a 404 route and component that will return if the route is not found:

现在,如果我们遇到未定义的路线会怎样? 让我们设置一个404路由和组件,如果找不到该路由,它将返回:

const NotFound = () => (  

404.. This page is not found!

)

Now, below our ‘/address’ route, create the following route:

现在, 我们的“ / address”路由下,创建以下路由:

Now, if we navigate to some route that has not been defined () , we should see our 404 route.

现在,如果导航到尚未定义的某些路由( ),则应该看到404路由。

Now, let’s add navigation to get us between pages.

现在,让我们添加导航以使我们在页面之间。

To do this, we will be using the <Link> component. <Link> is similar to using an html anchor tag.

为此,我们将使用<Link>组件。 <Link>类似于使用html锚标记。

From the docs:

从文档:

The primary way to allow users to navigate around your application. <Link> will render a fully accessible anchor tag with the proper href.
允许用户在您的应用程序中浏览的主要方式。 <Link>将呈现具有适当href的完全可访问的锚标记。

To do this, let’s first create a Nav component. Our Nav component will contain <Link> components, and will look like this:

为此,我们首先创建一个Nav组件。 我们的Nav组件将包含<Link>组件,如下所示:

const Nav = () => (  
Home 
Address
)

Now we need a way to make our Nav component persistent across all pages. To do this, we will wrap our child routes in a main <Route> component. We will also need to update our Home component, and create a new component called Container:

现在,我们需要一种使Nav组件在所有页面上持久保存的方法。 为此,我们将子路由包装在主<Route>组件中。 我们还需要更新Home组件,并创建一个名为Container的新组件:

Container:

容器:

const Container = (props) => 
{props.children}

{props.children} will allow any routes wrapped within this route to be rendered in this component.

{props.children}将允许将此路线中包含的所有路线呈现在此组件中。

Now, let’s rewrite our App component to look like this. We are wrapping our HomePage, Address and NotFound routes inside the new Container route. We are also setting HomePage to be our IndexRoute. That means that when we hit , our Home component will render, as it is specified as the index:

现在,让我们重写我们的App组件,使其看起来像这样。 我们将HomePage,Address和NotFound路由包装在新的Container路由内。 我们还将HomePage设置为我们的IndexRoute。 这意味着当我们点击 ,我们的Home组件将被渲染,因为它被指定为索引:

class App extends Component {  render () {    return (      
) }}

For reference, our full app.js code should look like .

作为参考,我们完整的app.js代码应如下 。

Now, when we navigate to , we should see our Home Component rendered, along with our Nav <Link> components!

现在,当我们导航到 ,应该看到渲染的Home组件以及Nav <Link>组件!

步骤5.多个子/ IndexRoutes (Step 5. Multiple child / IndexRoutes)

Now, let’s say we want to nest a twitter feed and an Instagram feed in our address component. Let’s create that functionality.

现在,我们要在地址组件中嵌套一个Twitter feed和一个Instagram feed。 让我们创建该功能。

First, let’s rewrite our address route to take two new components: InstagramFeed and TwitterFeed:

首先,让我们重写地址路由,以添加两个新组件:InstagramFeed和TwitterFeed:

class App extends Component {  render () {    return (      
) }}

We’ve set the IndexRoute of address to be TwitterFeed, and have added the Instagram route there as well.

我们将地址的IndexRoute设置为TwitterFeed,并在其中添加了Instagram路由。

Now, let’s create our InstagramFeed and TwitterFeed components. These will be very basic just so we know we’ve hit the correct routes:

现在,让我们创建我们的InstagramFeed和TwitterFeed组件。 这些将是非常基本的,所以我们知道我们已经找到了正确的路线:

const Instagram = () => 

Instagram Feed

const TwitterFeed = () =>

Twitter Feed

Finally, go into the Address component, and add the Links to the new components as well as props.children, so the components will be rendered:

最后,进入“地址”组件,并将“链接”添加到新组件以及props.children中,以便呈现这些组件:

const Address = (props) => 
Twitter Feed 
Instagram Feed

We are located at 555 Jackson St.

{props.children}

Now, when we navigate to , the address component should be rendered as well as the TwitterFeed component:

现在,当我们导航到 ,应该呈现地址组件以及TwitterFeed组件:

For reference, the code up to now should look like .

作为参考,到目前为止的代码应如下 。

We will now look at how to style to a Link based on whether the route is active. There are two main ways to do this, either adding style directly or through a class.

现在,我们将基于路径是否处于活动状态来研究如何为链接设置样式。 有两种主要方法可以做到这一点,直接添加样式或通过类添加样式。

From the docs:

从文档:

<Link> can know when the route it links to is active and automatically apply an activeClassName and/or activeStyle when given either prop. The <Link> will be active if the current route is either the linked route or any descendant of the linked route. To have the link be active only on the exact linked <IndexLink> instead or set theonlyActiveOnIndex prop.

<Link>可以知道它链接到的路由何时处于活动状态,并在给出任何一个道具时自动应用activeClassName和/或activeStyle。 如果当前路径是链接路径或连接路径的任何后代,则<Link>将处于活动状态 要使链接仅在确切的链接上处于活动状态 <IndexLink>或设置theonlyA ctiveOnIndex属性。

First, let’s look at activeStyle. To apply activeStyle, you simply add activeStyle as a property to a <Link> and pass in the styling you would like the <Link> to have:

首先,让我们看一下activeStyle。 要应用activeStyle,只需将activeStyle作为属性添加到<Link>中,然后传递您希望<Link>具有的样式:

Home

Let’s update our Nav component to implement this:

让我们更新Nav组件以实现此功能:

const Nav = () => (  
Home 
Address 
About
)

Now, let’s take a look at how this looks in our browser. You may notice that when you click on address, that Home is still highlighted:

现在,让我们看一下它在浏览器中的外观。 您可能会注意到,当您单击地址时,主页仍然突出显示:

This is because when using <Link> along with activeStyle, the <Link> will be active if the current route is either the linked route or any descendant of the linked route.

这是因为,当将<Link>与activeStyle一起使用时,如果当前路由是有符号路由或该有符号路由的任何后代 ,则<Link>将处于活动状态。

This means that because Address is a descendent of Home, it stays highlighted. To fix this, we can pass the onlyActiveOnIndex property to our Link component:

这意味着,由于Address是Home的后代,因此它将保持突出显示状态。 要解决此问题,我们可以将onlyActiveOnIndex属性传递给我们的Link组件:

Home

Now, when we look at our browser, the link will only be highlighted if we are on the exact link:

现在,当我们查看浏览器时,仅当我们在确切的链接上时,该链接才会突出显示:

There is also a sibling component of <Link> called <IndexLink>. <IndexLink> that is only active when the current route is exactly the linked route.

<Link>的同级组件也称为<IndexLink>。 <IndexLink>,仅当当前路径正好是链接路径时才激活。

From the docs:

从文档:

An <IndexLink> is l<Link>, except it is only active when the current route is exactly the linked route. It is equivalent to<Link> with the onlyActiveOnIndex prop set.

<IndexLink> <Link>相似,只是它仅在当前路由恰好是链接路由时才处于活动状态。 它等效于具有onlyActiveOnIndex属性集的<Link>。

To implement this, first bring in <IndexLink> from react-router:

要实现这一点,首先从react-router引入<IndexLink>:

import { ..., IndexLink } from 'react-router'

Now, simply replace the <Link> components in nav with <IndexLink> components:

现在,只需用<IndexLink>组件替换nav中的<Link>组件:

const Nav = () => (  
Home
 
Address
 
About
)

Now, how about adding classes vs styles? To do this, we can use activeClassName. Let’s set up an active style in our index.html:

现在,如何添加类与样式? 为此,我们可以使用activeClassName。 让我们在index.html中设置一个活动样式:

Now, we’ll replace activeStyle with activeClassName in our Nav component:

现在,我们将在Nav组件中将activeStyle替换为activeClassName:

const Nav = () => (  
Home
 
Address
 
About
)

For reference, our code should now look like .

供参考,我们的代码现在应如下 。

步骤7.命名组件 (Step 7. Named Components)

Using Named Components, we can specify component as props to a <Route>.

使用命名组件,我们可以将组件指定为<Route>的道具。

From the docs:

从文档:

When a route has one or more named components, the child elements are available by name on this.props. In this case this.props.children will be undefined. All route components can participate in the nesting.
当路由具有一个或多个命名组件时,子元素可通过this.props上的名称使用。 在这种情况下,this.props.children将是未定义的。 所有路线组件都可以参与嵌套。

Let’s now dig into the code and see how this would actually look.

现在,让我们深入研究代码,看看它的实际外观。

First, let’s create a new Component that will be rendering our Named Components. These components will be available as props:

首先,让我们创建一个将渲染命名组件的新组件。 这些组件将作为道具提供:

const NamedComponents = (props) => (  
{props.title}
{props.subTitle}
)

Next, let’s create two new components called Title and Subtitle:

接下来,让我们创建两个名为Title和Subtitle的新组件:

const Title = () => (  

Hello from Title Component

)const SubTitle = () => (

Hello from SubTitle Component

)

Now, let’s create a new route for our NamedComponents component, and define the Title and Subtitle components in the IndexRoute:

现在,让我们为NamedComponents组件创建一个新路由,并在IndexRoute中定义Title和Subtitle组件:

Finally, let’s add a link to our nav to navigate to this component:

最后,让我们添加到导航的链接以导航到该组件:

Named Components

Now, we should see our new Named Components link when we look at our browser, and when clicking on the link we should see our Title and SubTitle components rendering on the screen:

现在,当我们查看浏览器时,我们应该看到新的“命名组件”链接,单击链接时,我们应该在屏幕上看到“标题”和“子标题”组件的渲染:

For reference, our code should now look like .

供参考,我们的代码现在应如下 。

步骤8.路由参数 (Step 8. Route Parameters)

An essential part of many applications is the ability to read route parameters from a url.

许多应用程序的基本组成部分是能够从url读取路由参数的功能。

To implement this, let’s revisit our About component. First, let’s rewrite the path in our Router to take an optional parameter, we’ll call it name:

为了实现这一点,让我们重新访问About组件。 首先,让我们在路由器中重写路径以采用可选参数,我们将其命名为:

Now, let’s rewrite our About component to use this name variable:

现在,让我们重写About组件以使用此名称变量:

const About = (props) => (  

Welcome to the About Page

{props.params.name}

)

Now, if we visit we will see my name displayed below “Welcome to the About Page”.

现在,如果我们访问我们将在“欢迎使用关于页面”下方看到我的名字。

The only issue here is that if we revisit , we get a 404 because there is no name parameter. To fix this, we can make the parameter optional by wrapping it in parenthesis:

这里唯一的问题是,如果我们重新访问 ,则会得到一个404,因为没有名称参数。 为了解决这个问题,我们可以通过将参数包装在括号中来使参数成为可选参数:

Now, if we visit we no longer get a 404, and can still access the name variable.

现在,如果我们访问我们将不再获得404,并且仍然可以访问name变量。

We can also take this one step further by checking to see if props.name is available and displaying some content:

我们还可以通过检查props.name是否可用并显示一些内容来进一步迈出这一步:

{ props.params.name && 

Hello, {props.params.name}

}

Now, the content will only be shown if there is a name parameter available.

现在,仅在有名称参数可用时才显示内容。

For reference, our code should now look like .

供参考,我们的代码现在应如下 。

步骤9.查询字符串参数 (Step 9. Query String Parameters)

You can also pass in query strings as props to any component that will be rendered at a specific route, and access these parameters as props.location.query.

您还可以将查询字符串作为prop传递给将在特定路线呈现的任何组件,并以props.location.query的形式访问这些参数。

To see how this works, let’s create a new component called Query, and render a property called props.location.query.message:

为了了解其工作原理,让我们创建一个名为Query的新组件,并渲染一个名为props.location.query.message的属性:

const Query = (props) => (  

{props.location.query.message}

)

Now, let’s set up our new Query Route within the address route we already have created:

现在,让我们在已经创建的地址路由中设置新的查询路由:

...
...

Finally, let’s link to this route by creating a new Link component, and passing in a query string called message and giving it a value. This is done in the ‘to’ property that we have already used.

最后,通过创建一个新的Link组件,并传递一个名为message的查询字符串并为其提供值,来链接到此路由。 这是在我们已经使用的“ to”属性中完成的。

Instead of passing a link to ‘to’, we instead pass in an object the the pathname and query properties defined:

而不是传递到“ to”的链接,我们传递的是定义了路径名和查询属性的对象:

Route Query

Now, if we click on our Route Query link, we should see our message rendered on the screen:

现在,如果单击“路线查询”链接,我们应该在屏幕上看到呈现的消息:

For reference, our code should now look like .

供参考,我们的代码现在应如下 。

That covers many basic use cases for getting started with React Router.

这涵盖了React Router入门的许多基本用例。

My Name is . I am a developer at where we help educators make smart instructional decisions by providing all their data in one place. Check us out

我叫 。 我是一名开发人员,我们在一个地方提供所有数据,帮助教育工作者做出明智的教学决策。 检查我们

If you like React and React Native, checkout out our podcast — on

如果您喜欢React和React Native,请查看我们的播客上的

If you enjoyed this article, please recommend and share it! Thanks for your time
如果您喜欢这篇文章,请推荐并分享! 谢谢你的时间

翻译自:

转载地址:http://veewd.baihongyu.com/

你可能感兴趣的文章
Qt之模拟时钟
查看>>
第一次接触安卓--记于2015.8.21
查看>>
(转)在分层架构下寻找java web漏洞
查看>>
mac下多线程实现处理
查看>>
C++ ifstream ofstream
查看>>
跟初学者学习IbatisNet第四篇
查看>>
seL4环境配置
查看>>
Git报错:insufficient permission for adding an object to repository database .git/objects
查看>>
ajax跨域,携带cookie
查看>>
BZOJ 1600: [Usaco2008 Oct]建造栅栏( dp )
查看>>
nginx 高并发配置参数(转载)
查看>>
洛谷 CF937A Olympiad
查看>>
Codeforces Round #445 C. Petya and Catacombs【思维/题意】
查看>>
用MATLAB同时作多幅图
查看>>
python中map的排序以及取出map中取最大最小值
查看>>
ROR 第一章 从零到部署--第一个程序
查看>>
<form>标签
查看>>
vue去掉地址栏# 方法
查看>>
Lambda03 方法引用、类型判断、变量引用
查看>>
was集群下基于接口分布式架构和开发经验谈
查看>>