博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hitchhiker部署_Hitchhiker的React Router v4指南:20分钟内完成Grok React Router
阅读量:2523 次
发布时间:2019-05-11

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

hitchhiker部署

Hi fellow React Hitchhiker! Want a ride into React Router? Jump in. Let’s go!

大家好,React Hitchhiker! 想要乘坐React Router吗? 跳进去吧!

To understand the philosophy behind React Router, we need to know what a Single-Page Application (SPA) is.

要了解React Router背后的原理,我们需要知道什么是单页应用程序(SPA)。

什么是单页应用程序? (What Is A Single-Page Application?)

Basically it’s a web application or web site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.

基本上,它是一个Web应用程序或网站,它通过动态重写当前页面而不是从服务器加载整个新页面来与用户交互。

为什么这么好?! (Why is this so good?!)

1. avoids interruption of the user experience between successive pages

1.避免连续页面之间的用户体验中断

2. makes the application behave more like a desktop application

2.使应用程序的行为更像桌面应用程序

3. all the code resources are dynamically loaded and added to the page as necessary, usually in response to user actions

3.通常会响应用户操作,将所有代码资源动态加载并根据需要添加到页面中

4. because it’s kewl and kewl and extra-ultra-wide-4K-level-of-kewl. ?

4.因为它是海螺和海螺以及超宽4K级的海螺。 ?

SPAs are an industry standard now, and lots of companies are in a quest to find programmers to develop their projects.

SPA现在是一种行业标准,许多公司都在寻找程序员来开发他们的项目。

什么是React Router? (What is React Router?)

React Router is a tool that allows you to handle routes.

React Router是一个允许您处理路由的工具。

Since you’re dealing with an SPA, you need a way to trigger the contents that are loaded on the screen. React Router introduces a concept called “Dynamic Routing”, which is quite different from the “Static Routing” we are used to.

由于您正在处理SPA,因此需要一种方法来触发屏幕上加载的内容。 React Router引入了一个称为“动态路由”的概念,它与我们过去习惯的“静态路由”有很大的不同。

When you’re dealing with “Static Routing” you declare your routes as part of your app’s initialisation before any rendering takes place (Rails, Express, Ember, Angular, and so on).

在处理“静态路由”时,您会在进行任何渲染(Rails,Express,Ember,Angular等)之前,将路由声明为应用程序初始化的一部分。

“Dynamic Routing” means that routing takes place as your app is rendering, not in a configuration or convention outside of a running app.

“动态路由”是指在您的应用渲染时进行路由,而不是在运行的应用之外进行配置或使用约定。

React Router v4 advocates and implements a component-based approach to routing.

React Router v4提倡并实施基于组件的路由方法。

It provides different Routing Components according to the needs of the application and platform.

它根据应用程序和平台的需求提供不同的路由组件。

In this specific case we’re going to explore  <BrowserRouter> because we want to use “dynamic routing” in a “web app” context and leave the other ones for other circumstances.

在此特定情况下,我们将探索<BrowserRouter>,因为我们想在“ Web应用程序”上下文中使用“动态路由”,而将其他路由留给其他情况使用。

谁创建了React Router? (Who Created React Router?)

These two amazing human beings, and . And they deserve loads, tons of claps! Together they started .

这两个惊人的人, 和 。 他们应该承担重担,拍手成吨! 他们一起开始了 。

Nowadays, correct me if I’m wrong, they followed separate paths:

如今,如果我错了,请纠正我,它们遵循不同的路径:

Michael Jackson continues to develop .

迈克尔·杰克逊(Michael Jackson)继续开发 。

Ryan Florence created .

Ryan Florence创建了 。

React Router与Redux有关系吗? (Has React Router Anything To Do With Redux?)

No. Although they typically appear together.

不。尽管它们通常一起出现。

Are you sure? Yes ? I am sure ?

你确定吗? 是啊 我确定 ?

They’re both great and indispensable tools and as they are Higher Order Components (basically JavaScript functions that take a Component and return a new one), so it’s common to find them “composed” together.

它们既是很棒的工具,也是必不可少的工具,因为它们是高阶组件(基本上是使用Component并返回一个新组件JavaScript函数),因此通常将它们“组合”在一起。

设置,让我们脏手 (Setup, Let’s Get Our Hands Dirty)

To guide you through this process we’ll use Create React App (CRA).

为了指导您完成此过程,我们将使用Create React App(CRA)。

In the end you’ll have a clean boilerplate to build simple websites.

最后,您将获得一个干净的样板来构建简单的网站。

If by any chance or are beyond your grasp, I recommend you to first get into those and then come back with a cup of coffee.

如果您无法控制或 ,我建议您先进入其中,然后再喝杯咖啡。

Okay, to those who stood with me: after installing CRA, you need to install the react-router package.

好的,对那些支持我的人来说:安装CRA之后,您需要安装react-router软件包。

If you use npm just open your terminal, go to your CRA folder and type:

如果使用npm,只需打开终端,然后转到CRA文件夹并键入:

npm i -S react-router-dom

npm i -S react-router-dom

or

要么

yarn add react-router-dom if you use yarn as your package manager.

yarn add react-router-dom 如果您使用yarn作为您的包管理器。

Just to check your package.json and make sure everything is okay, here’s mine:

只是检查你的package.json 并确保一切正常,这是我的:

As you can see ?at this point we have react-router-dom as a dependency.

如您所见,至此,我们已经将react-router-dom作为依赖项。

Done, npm or yarn start and…

完成,npm或纱线开始并…

Bang! We’re riding Ma!

砰! 我们骑着马!

我们正在构建的应用程序 (The App We Are Building)

Let’s do a simple personal website with a navigation bar that allows the user to switch between content. Our website will have three main sections called Home, About and Topics.

让我们做一个带有导航栏的简单个人网站,该导航栏允许用户在内容之间进行切换。 我们的网站将有三个主要部分,分别称为“ 首页” ,“ 关于”和“ 主题”

The NavBar will be an omnipresent component while the Home, About and Topics will be rendered below according to the routes selected.

导航栏将是一个无所不在的组件,而HomeAboutTopics将根据选择的路线显示在下面。

Are you seeing the browser URL: localhost:3000/home in the screenshot below?

您是否在下面的屏幕快照中看到浏览器URL: localhost:3000 / home

It means that the Home route is triggered and the Home view is rendered.

这意味着将触发Home路线并渲染Home视图。

This will be our final result:

这将是我们的最终结果:

And this… ?, this is a website?

这……,这是一个网站?

? Yes, It is!

? 是的!

A naked one! Just try not to feel bias towards other complexities like styling and so on! I don’t want you to be distracted with anything other than grokking how simple it is to implement React Router v4.

赤裸的! 请尽量不要对其他复杂性(如样式等)产生偏见! 我不想让您因为专注于实现React Router v4的 简单性而分心。

So, after you’ve recovered from the shock, ?, let’s take the next step and see my /src/index.js file.

因此,在您从震惊中恢复后,?,让我们继续下一步,查看我的/src/index.js文件。

/src/index.js (/src/index.js)

index.js is the first file to be loaded by CRA, the initialisation point of everything in your App.

index.js是CRA加载的第一个文件,是应用程序中所有内容的初始化点。

Let’s take a look at what I’ve done:

让我们看看我做了什么:

So what are we doing here?

那我们在这里做什么?

  • We are importing the <BrowserRouter/> component from the dependency we’ve installed and stating that we’re going to call it <Router/> from this point on:

    我们将从已安装的依赖项中导入<BrowserRouter />组件,并声明从现在开始将其称为<Router />

import { BrowserRouter as Router } from ‘react-router-dom’;

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

  • We are importing a <Routes/> component, created by me, with the routes we’re going to use in our web site — don’t worry right now with this Component:

    我们正在导入一个由我创建的<Routes />组件,其中包含我们将在我们的网站中使用的路由-现在不用担心此组件:

import { Routes } from ‘./routes’;

import { Routes } from './routes';

The <Routes/> component is taking the place of the default CRA  <App/> component. It’s basically the same — I just called it <Routes/> because I feel it makes sense to turn the code more meaningful and readable.

<Routes />组件取代了默认的CRA <App />组件。 基本上是一样的-我只是将其称为<Routes />,因为我认为使代码更有意义和更具可读性是有意义的。

You are not loading an unique App anymore but a Routes component that will handle the routes and will trigger the mounting and rendering of the components which shall load within each route.

您不再要加载唯一的App,而是要加载一个Routes组件,该组件将处理路径并触发将在每个路径内加载的组件的安装和渲染。

  • We are embracing <Routes/> with the <Router/> component.

    我们将<Routes /><Router />组件结合在一起。

As a matter of fact, <Router/> works as a that only knows its children in the future and interacts with them in a more wide scope, independently of who and how many they are.

实际上, <Router />是一个 ,它将来只知道其子代,并且在更大范围内与它们交互,而与他们是谁和多少无关。

You do not have to worry about how it works to use it. This is a much deeper and advanced matter.

您不必担心它如何使用。 这是一个更深层次的问题。

Just make sure you understand that React.DOM is not anymore loading a simple App. It’s loading the App embraced by a Component called Router that in a higher instance or scope can interact with it and with the browser DOM.

只要确保您了解 React.DOM不再加载一个简单的App 。 它正在加载由称为Router的组件所包含的App,该组件在更高的实例或作用域中可以与其交互以及与浏览器DOM交互。

<Routes />组件 (<Routes /> Component)

那么, routes.js基本上是做什么的? (So basically what does routes.js do?)

It starts by importing React and a few components we’ll take a look later. Just think of them as simple stateless components: Home, About, TopicList, TopicDetail, NavBar and NoMatch.

首先从导入React和一些组件开始,我们稍后再看。 只是把它们当作简单的无状态的组件: 主页关于题目列表 ,TopicDetail,的NavBar NOMATCH。

It also imports three components from the react-router-dom package which we’ll need to invoke: <Route/>, <Switch/>and <Redirect/>.

它还从react-router-dom包中导入了我们需要调用的三个组件: <Route /><Switch /><Redirect />

After the imports, we export the stateless component Routes which invokes the NavBar (which will be always in the screen) and a <Switch/> component.

导入后,我们导出无状态组件Routes,该组件调用NavBar (将始终在屏幕中)和<Switch />组件。

这个<Switch />家伙做什么? (What does this <Switch/> guy do?)

This component basically renders the first child <Route> or <Redirect> that matches the browser location.

此组件基本上呈现与浏览器位置匹配的第一个子<Route><Redirect>

It starts to test stuff like this: “is the browser URL in this <Route/> path? No? Okay.” Next Route. “Is the browser URL in this other route path? No.”

它开始测试如下内容:“浏览器URL是否在此<Route />路径中? 没有? 好的。” 下一路线。 “浏览器URL是否在这条其他路径中? 没有。”

Next Route. “Oh, I got it! It’s in this one, let’s trigger the Component render and finish the checking by now (I don’t care with the other routes below…)”

下一路线。 “哦,我明白了! 正是在这个过程中,让我们触发Component渲染并立即完成检查(我不在乎下面的其他路线……)”

If by any chance this happens:

如果发生这种情况:

the second route will never be triggered because Switch will jump off before reaching it. He just goes to have a coffee… (and me too!!! ? Back!)

第二条路由将永远不会被触发,因为Switch会在到达它之前跳开。 他只是去喝咖啡……(我也是!!!回来!)

Inside <Switch/> we define each <Route/>.

<Switch />内部,我们定义每个<Route />

Each <Route/> tells this to the browser:“Hey browser DOM! If <Switch/> chooses me because your location is (exactly) this one, please render the following Component”.

每个<Route />告诉浏览器:“嘿,浏览器DOM! 如果<Switch />之所以选择我,是因为您的位置恰好是此位置,请呈现以下组件”。

Or in other cases such as the one below, it says:“Hey, browser, if by any instance your <Switch/> chose me because location is /Topics/”something” render Component Topic Detail. Certainly it’ll find out who is this :topicId (variable) thing that the user is asking us to match and route it accordingly”.

或在其他情况下(例如下面的情况)说:“嘿,浏览器,无论如何,您的<Switch />选择我是因为位置是/ Topics /” something”渲染组件主题详细信息。 当然,它将发现用户要求我们进行匹配并进行相应路由的:topicId (变量)是谁”。

Okay everyone. Because <Switch/> has this default behavior of checking each route, we need to provide a fallback in case it doesn’t match anything:

大家好 因为<Switch />具有检查每个路由的默认行为,所以我们需要提供一个后备,以防它不匹配任何内容:

This last Route simply renders a default page stating that no route was matched, kind of an error.

最后一条路由仅呈现一个默认页面,指出没有路由被匹配,这是错误。

Remember that here we’re dealing with an SPA and with “Dynamic Routing” so this is a simulation as if we were demanding routes to a server ?. Actually we’re not!

记住,这里我们正在处理SPA和“动态路由”,所以这是一种模拟,好像我们需要到服务器的路由一样。 其实我们不是!

We just do not know what to render if the user, for instance, inserts something not mismatched into the URL like this: http://localhost:3000/HelloWorld.

例如,如果用户在URL中插入了不匹配的内容,例如: http:// localhost:3000 / HelloWorld ,我们只是不知道要呈现什么。

As this route was not defined, we provide a NoMatch component to inform them about the non-existence of the route.

由于未定义此路线,因此我们提供了NoMatch组件,以告知他们该路线不存在。

<Redirect/> is there because if the user tries to load the URL without any route http://localhost:3000/, it would get a NoMatch because there’s no route defined for it. So the best way to handle this is make use of  <Redirect/> and push the user to the route of /Home which is by default our first screen of the app.

<Redirect />之所以存在,是因为如果用户尝试在没有任何路由http:// localhost:3000 /的情况下加载URL,则将获得NoMatch,因为没有为其定义任何路由。 因此,处理此问题的最佳方法是使用<Redirect />并将用户推送到/ Home的路由,默认情况下,这是我们应用程序的第一个屏幕。

为什么这是必要的? (Why is this necessary?)

Again, because usually the user would start the Application by typing it’s general URL and without the <Redirect/> the first rendered component would  be <NoMatch/>. We don’t want that, we want the user to be redirected to  the <Home/> component.

同样,因为通常用户将通过键入应用程序的一般URL来启动应用程序,而没有<Redirect />,则第一个呈现的组件将是<NoMatch /> 。 我们不希望那样,我们希望将用户重定向到<Home />组件。

视图和/或组件 (Views And / Or Components)

At this point in our guide, I’d like to stop a little bit to differentiate a View from a Component. This is not the essence of this guide, but will make sense after I show you the folder structure of my CRA.

现在,在我们的指南中,我想稍作停留以区分View与Component。 这不是本指南的本质,但是在我向您展示了我的CRA的文件夹结构之后才有意义

When we are “” and we start making an App, and it starts to grow, sometimes we stop because we feel things are not in the right place.

当我们“ ”并开始制作一个应用程序,并且它开始增长时,有时我们会停下来,因为我们觉得事情做错了。

This means that we need to give names to those things and keep them separated in different “drawers” or ”folders”.

这意味着我们需要给这些东西起个名字,并将它们分开放在不同的“抽屉”或“文件夹”中。

Views and Components are things that are painted on screen. So what differentiates one thing from the other?

视图和组件是画在屏幕上的东西。 那么,一件事与另一件事有什么区别呢?

And are views not components? And components are not views?

而且视图不是组件吗? 而且组件不是视图?

Well, in terms of coding language, a View and a Component are certainly functions or classes — stateless components or stateful components as we call it in React lingo.

好吧,就编码语言而言,视图和组件无疑是函数或类-无状态组件或有状态组件,正如我们在React术语中所称的那样。

So what does differentiate them?

那么,它们有什么区别呢?

Well, a View has a route. Inside this View you can render a lot of components.

好吧,一个视图有一条路线。 在此视图中,您可以渲染很多组件。

A component usually is an abstraction that can be invoked a lot of times in different views. It can be a button, a form, a chart. It can even be a more complex thing, while a view is unique and has a route.

组件通常是一种抽象,可以在不同的视图中多次调用。 它可以是按钮,表单,图表。 尽管视图是唯一的并且具有路线,但它甚至可能是更复杂的事情。

This is a very simple concept that must be understood at the beginning, as soon as we start doing an app so small as a personal homepage.

这是一个非常简单的概念,在我们开始制作像个人主页一样小的应用程序之初,就必须首先理解它。

Let’s take a look at my CRA folder structure:

让我们看一下我的CRA文件夹结构:

So, as you can see I — and 99% of the world — like to keep oranges and pears in different baskets. And so do you! I have faith in you! I trust you!

因此,如您所见,我以及全世界99%的人都喜欢将橘子和梨放在不同的篮子里。 你也是! 我相信你! 我信任你!

There are a lot of patterns on how to organize this stuff and a lot of discussion starts when we introduce more packages like Redux that transform a little bit the architecture of the app, or when we want to paint on the screen Dashboards, Widgets, Cycling Pigs or more weird stuff…

关于如何组织这些东西的模式很多,当我们引入更多的软件包(例如Redux)来改变应用程序的体系结构时,或者当我们想要在屏幕上绘制仪表板,小部件,自行车时,就会有很多讨论。猪或更多奇怪的东西……

But, to differentiate concepts, take a careful look at Views and Components.

但是,为了区分概念,请仔细查看“视图和组件”。

Home, About, TopicList and NoMatch are views. They have their own proper routes that trigger them.

主页关于题目列表NOMATCH的意见。 它们具有触发它们的适当路径。

NavBar is an omnipresent component that’s always invoked. It doesn’t have a route.

NavBar是一个无所不在的组件,总是被调用。 它没有路线。

TopicDetails is a component that will display Topic info when the TopicList/:topicId route is triggered. It’s a reusable component that can be imported into other places and refactored or extended. It doesn’t have a specific route.

TopicDetails是一个组件,当触发TopicList /:topicId路由时将显示主题信息。 这是一个可重用的组件,可以导入到其他地方并进行重构或扩展。 它没有特定的路线。

主页/关于视图 (The Home / About Views)

Inside the Home folder, I have an index.js and a Home.js file.

在Home文件夹中,我有一个index.js和一个Home.js文件。

Having an index.js to export the other files is a good practice. Just trust me or bring some wine because this will be a long talk ?

有一个index.js来导出其他文件是一个好习惯。 相信我还是带些酒,因为这将是一段漫长的谈话?

… oh, let’s just drink the wine and we will talk later! ?

……哦,让我们喝点酒,我们待会儿再谈! ?

This is a simple view that only exports its title. The About view is equal to this one.

这是一个简单的视图,仅导出其标题。 About视图等于此视图。

Now let’s take a look at the TopicList View because it’s a little bit different.

现在让我们看一下TopicList视图,因为它有点不同。

TopicList和TopicDetail视图 (TopicList and TopicDetail Views)

So TopicList View has this detail of handling different routes. Remember that /Topic/:topicId route that <Route/> told <Switch/> to let TopicDetail handle?

因此TopicList视图具有处理不同路由的详细信息。 还记得<Route />告诉<Switch />TopicDetail处理的/ Topic /:topicId路由吗?

Here we are with that.

我们在这里。

TopicList receives { match } as a prop. Don’t let the destructuring feature scare you. We could simply receive props and call props.match. This is simply how all the cool kids nowadays destructure props to improve readability and React flow. I also like it a lot! This is kind of like picking up a box with your mobile inside or picking up the mobile directly. As a matter of fact it was kept inside the box but at this moment you only need to check your e-mail ? so let the box stay where it is! Don’t bring it with you to work!

TopicList接收{match}作为道具。 不要让破坏功能吓到您。 我们可以简单地接收props并调用props.match 。 这就是当今所有酷孩子如何分解道具以提高可读性和React流的方式。 我也很喜欢! 这有点像拿起手机放在盒子里或直接拿起手机。 事实上,它被保留在盒子里,但是现在您只需要检查您的电子邮件? 所以让盒子留在原处! 不要随身携带它!

Anyways, let’s keep focused on code.

无论如何,让我们继续专注于代码。

In this file, we import a Component from React Router called { Link } because we want to create Links ?

在此文件中,由于要创建链接,我们从React Router导入了一个名为{Link}的组件。

We receive a match from the Route we’ve chosen when we’ve clicked Topics and we are rendering an unordered list with 3 options: Topic1, Topic2 and Topic3.

当我们单击“ 主题”时,我们会从选择的路线中收到一个匹配项,并且正在渲染具有3个选项的无序列表: Topic1Topic2Topic3

Basically if the User chooses Topic1 Link in the screen, the <Link/> will push the browser URL to that path /Topics/Topic1.

基本上,如果用户在屏幕上选择Topic1链接 ,则<Link />会将浏览器URL推送到该路径/ Topics / Topic1

What happens next? <Router/> and <Switch /> detect that the URL changed and take a look into their info to check what route needs to be fired. So they discover that now the route triggered is `the one for /Topics/:topicId and triggers TopicDetail rendering. TopicDetail will render Topic1 details.

接下来发生什么? <Router /><Switch />检测到URL更改,并查看其信息以检查需要触发的路由。 因此,他们发现现在触发的路由是/ Topics /:topicId的路由,并触发TopicDetail呈现。 TopicDetail将呈现Topic1详细信息。

TopicDetail receives match from the Router and renders the topicId located at match.params.topicId.

TopicDetail接收来自路由器的比赛 ,并呈现位于match.params.topicIdtopicId。

NavBar组件 (The NavBar Component)

The NavBar component has a special role here because it’s omnipresent.

NavBar组件在这里具有特殊的作用,因为它无处不在。

Its function is to allow the user to navigate the website and to show the sections (routes) available.

其功能是允许用户浏览网站并显示可用的部分(路线)。

As you’ve seen in the beginning, it’s inside <Router/> but outside <Switch/> so any view will always be composed with NavBar on top.

正如您在一开始所看到的,它在<Router />之内,但在<Switch />之外,因此任何视图都将始终由NavBar组成。

As you can see, its role is basic. It only supplies <Link/> and tells <Router/> to ask <Switch/> to trigger the chosen <Route/> and render it on screen.

如您所见,它的作用是基本的。 它仅提供<Link />并告诉<Router />要求<Switch />触发所选的<Route />并将其呈现在屏幕上。

最后但并非最不重要的 (Last but not least)

I think that by this time you probably have a basic understanding of how React Router works and can be used to do a simple website.

我认为到这时您可能已经对React Router的工作方式有了基本的了解,并且可以用来创建一个简单的网站。

If you want to check the code or test it you can pull my repo, available on .

如果您想检查或测试代码,可以拉我的仓库,可以在上 。

参考书目 (Bibliography)

To make this article, I’ve used the React Router documentation that you can find .

为了撰写本文,我使用了React Router文档,您可以在找到。

All the other sites I’ve used are linked along the document to add info or provide context to what I’ve tried to explain to you.

我使用过的所有其他网站都与文档链接在一起,以添加信息或提供与我尝试向您解释的内容的上下文。

This article is part 1 of a series called “Hitchhiker’s Guide to React Router v4.” Parts 2–4 coming to freeCodeCamp throughout this week!

本文是称为“ Hitchhiker的React Router v4指南”系列的第1部分。 整个星期,第2–4部分将进入freeCodeCamp!

Thank you very much!

非常感谢你!

翻译自:

hitchhiker部署

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

你可能感兴趣的文章
Ruby数组的操作
查看>>
hdu1181暴搜
查看>>
解码字符串 Decode String
查看>>
json学习笔记
查看>>
工具:linux 性能监控工具-nmon
查看>>
fatal error C1853
查看>>
Ural 1001 - Reverse Root
查看>>
玩转webpack之webpack的entry output
查看>>
java 操作mongodb查询条件的常用设置
查看>>
黑马程序员_java基础笔记(02)...java语言基础组成
查看>>
关于缓存击穿
查看>>
对innodb 拷贝文件实现数据库的方式(转)
查看>>
python知识点 2014-07-09
查看>>
FloatingActionButton的一点学习感悟
查看>>
ABAP CDS ON HANA-(10)項目結合して一つ項目として表示
查看>>
网站地址信息
查看>>
产品经理 - 登录 注册
查看>>
小白的python进阶历程------05.占位符
查看>>
CF414BMashmokh and ACMDP
查看>>
Notepad++ 通过g++编译
查看>>