博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用React Router v4进行条件路由
阅读量:2507 次
发布时间:2019-05-11

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

When building React applications, one thing developers don’t like to utilize is routing in React - usually because of the assumed learning curve involved. In this article, we are going to debunk that myth and show you how easy it is to implement routing and serving responsive routes in your React applications.

在构建React应用程序时,开发人员不喜欢使用的一件事就是在React中进行路由-通常是因为涉及了假定的学习曲线。 在本文中,我们将揭穿这个神话,并向您展示在您的React应用程序中实现路由和提供响应路由是多么容易。

In layman’s terms, responsive routing is pretty much serving different routes to users based on the viewport of their device. CSS media queries are usually used to achieve this. The only issue with this is the fact that with media queries, you’re restricted to either showing or not showing different elements by using the CSS props. With responsive routes, you can now serve entire separate views our React applications to different users based directly on their screen sizes.

用通俗易懂的术语来说,响应式路由几乎可以根据用户设备的视口为用户提供不同的路由。 CSS媒体查询通常用于实现此目的。 唯一的问题是,对于媒体查询,您只能使用CSS道具来显示或不显示其他元素。 通过响应式路由,您现在可以直接根据他们的屏幕尺寸为不同的用户提供我们的React应用程序的整个单独视图。

( )

In this tutorial, we will see how to build a simple user dashboard application that serves different routes to users based on the size of their device screens.

在本教程中,我们将看到如何构建一个简单的用户仪表板应用程序,该应用程序根据用户设备屏幕的大小向用户提供不同的路由。

Responsive Routing Demo

( )

To follow through adequately, you’ll need the following:

要充分遵循,您需要满足以下条件:

  • NodeJS installed on your machine

    您机器上安装的NodeJS
  • NPM installed on your machine

    NPM安装在您的计算机上

To confirm your installations, run the following command:

要确认您的安装,请运行以下命令:

node --versionnpm --version

If you get their version numbers as results, then you’re good to go

如果您得到他们的版本号作为结果,那您就很好了

( )

安装React (Installing React)

This article is based on React you need to have it installed on your machine. To install React, run the following command:

本文基于React,您需要在机器上安装它。 要安装React,请运行以下命令:

npm install -g create-react-app

Once this is done, your have successfully installed React on your machine. And we can go ahead to create our new each application by running the command:

一旦完成,您就已经在机器上成功安装了React。 我们可以通过运行以下命令继续创建新的每个应用程序:

create-react-app responsive-routingcd responsive-routing

Next thing to do is to install the necessary modules we would need to successfully build this demo. These modules are the react-router-dom and react-media. We install this by running the command:

接下来要做的是安装成功构建此演示所需的必要模块。 这些模块是react-router-domreact-media 。 我们通过运行以下命令进行安装:

npm install react-router-dom react-media

Now, we can start the application by running the command:

现在,我们可以通过运行以下命令来启动应用程序:

npm start

( )

The Github logo in the center of the page serves as the navigation part of our application. Let's see how to make that. In your src/ folder, create a new folder called Nav and the following files as follows:

页面中央的Github徽标用作我们应用程序的导航部分。 让我们看看如何做到这一点。 在src/文件夹中,创建一个名为Nav的新文件夹,并创建以下文件,如下所示:

cd src    mkdir Nav    cd Nav && touch index.js Nav.css

You’ll need to add the Github logo and save it as logo.svg you can download it from

您需要添加Github徽标并将其另存为logo.svg您可以从下载

Now, update the src/Nav/index.js file to look like this:

现在,将src/Nav/index.js文件更新为如下所示:

// src/Nav/index.js    import React from 'react';    import './Nav.css';    import logo from './logo.svg';    const Nav = () => (      
); export default Nav;

The navigation component has the following styling:

导航组件具有以下样式:

/** src/Nav/Nav.css **/    nav {
display: flex; justify-content: center; height: 50px; margin-bottom: 10px; } nav > img {
display: block; width: 50px; height: auto; }

Now, let render the Nav component. To do this, let’s edit the default src/App.js file to look like this:

现在,渲染Nav组件。 为此,我们将默认的src/App.js文件编辑如下:

// src/App.js    import React, {
Component } from 'react'; import Nav from './Nav'; = App extends Component {
render() {
return (
); } } export default App;

Now, when we run our application using npm start and head over to the browser, we get the following:

现在,当我们使用npm start运行应用npm start并转到浏览器时,将得到以下信息:

Navigation Component

( )

The user cards are responsible for displaying details of the user. Now, let’s see how to create this. In the src/ directory of your app, create a new Users folder and create the following files:

用户卡负责显示用户的详细信息。 现在,让我们看看如何创建它。 在应用程序的src/目录中,创建一个新的Users文件夹并创建以下文件:

mkdir Users    cd Users && touch UsersCard.js UsersCard.css

Edit the UsersCard.js file to look like this:

编辑UsersCard.js文件,如下所示:

// src/Users/UsersCard.js    import React from 'react';    import {
Link} from 'react-router-dom'; import './UsersCard.css' const UsersCard = ({
user, match }) =>

{

user.name}

@{

user.username}

{

user.followers}

Followers

{

user.following}

Following

{

user.repos}

Repositories
; export default UsersCard;

If you pay attention to the code snippet above, we used the Link component from the react-router-dom to allow the user navigate to view details of a single user when the card is clicked. So, for a given user card with an id of 10009 and the Link component will generate a URL like this:

如果您注意上面的代码段,我们使用了react-router-domLink组件,以允许用户导航以单击该卡时查看单个用户的详细信息。 因此,对于给定id10009用户卡,“ Link组件将生成如下URL:

http://your-app/current-page/10009
  • http://your-app/current-page represents existing URL

    http://your-app/current-page代表现有网址
  • 10009 represents the user id.

    10009代表用户ID。

All this information will be passed when the component is rendered. The component has the following styling:

所有这些信息将在渲染组件时传递。 该组件具有以下样式:

/** src/Nav/UsersCard.css **/    .card {
border-radius: 2px; background-color: #ffffff; box-shadow: 0 1.5px 3px 0 rgba(0, 0, 0, 0.05); max-width: 228px; margin: 10px; display: flex; flex-direction: column; align-items: center; padding: 0; } .card img {
width: 50px; height: auto; border-radius: 50%; display: block; padding: 15px 0; } .users-card__name {
font-weight: 400; font-size: 16.5px; line-height: 1.19; letter-spacing: normal; text-align: left; color: #25292e; } .users-card__username {
font-size: 14px; color: #707070; } .users-card__divider {
border: solid 0.5px #efefef; width: 100%; margin: 15px 0; } .users-card__stats {
display: flex; } .users-card__stats p {
font-size: 20px; } .users-card__stats div {
margin: 10px; text-align: center; } .users-card__stats span {
color: #707070; font-size: 12px; }

( )

UsersList

What we see above is a listing of users. To get our application to look like this, we need to first create a UsersList component. In the src/Users directory, create the following files:

我们上面看到的是用户列表。 为了使我们的应用程序看起来像这样,我们需要首先创建一个UsersList组件。 在src/Users目录中,创建以下文件:

touch UsersList.js UsersList.css

To display the UserCards in the above format, we need to do some heavy lifting - don’t worry, i’ll be your hypeman.

要以上述格式显示UserCard,我们需要做一些繁重的工作-不用担心,我将成为您的炒作。

Let’s edit the UsersList.js as follows. First, we make the necessary imports:

让我们如下编辑UsersList.js 。 首先,我们进行必要的导入:

// src/Users/UsersList.js    import React from 'react';    import UsersCard from './UsersCard';    import './UsersList.css';    const listOfUsersPerRow = (users, row, itemsPerRow, match) =>      users        .slice((row - 1) * itemsPerRow, row * itemsPerRow)        .map(user => 
); const listOfRows = (users, itemsPerRow, match) => {
const numberOfUsers = users.length; const rows = Math.ceil(numberOfUsers / itemsPerRow); return Array(rows) .fill() .map((val, rowIndex) => (
{
listOfUsersPerRow(users, rowIndex + 1, itemsPerRow, match)}
)); }; //...

The listOfUsersPerRow and listOfRows functions work hand in hand to ensure that we have not more than the specified number cards on each row. Next thing to do is then use the functions to create the listing of the users as follows

listOfUsersPerRowlistOfRows函数可以协同工作,以确保每行上的指定号码卡的数量不超过指定数量。 接下来要做的是使用这些函数来创建用户列表,如下所示

//src/Users/UsersList.js    //...     const UsersList = ({
users, itemsPerRow = 2, match }) => (

Users

{
listOfRows(users, itemsPerRow, match)}
); export default UsersList;

The UsersList.css will look like this:

UsersList.css将如下所示:

/** src/Users/UsersList.css **/    .cards {
margin-left: 20px; } .columns {
margin-top: 0; }

( )

Creating User Details

When a single user card is clicked from the listing of users, the single user card is displayed under a details section. Let’s see how to make this component.

当从用户列表中单击单个用户卡时,该单个用户卡将显示在详细信息部分下。 让我们看看如何制作这个组件。

Create the following files in the src/Users directory:

src/Users目录中创建以下文件:

touch UsersDetails.js UsersDetails.css

Now, let’s add the following to the UsersDetails.js file:

现在,将以下内容添加到UsersDetails.js文件中:

// src/Users/UsersDetails.js    import React from 'react';    import UsersCard from './UsersCard';    const UsersDetails = ({
user, match }) =>

Details

; export default UsersDetails;

( )

The dashboard component is simple. We display the UserList and when a card is clicked, display the details on the side of the screen without having to reload the page. Let’s see how to make it work. Create a UsersDashboard.js file in the Users directory:

仪表板组件很简单。 我们显示UserList ,单击卡后,无需重新加载页面即可在屏幕侧面显示详细信息。 让我们看看如何使其工作。 在Users目录中创建一个UsersDashboard.js文件:

touch UserDashboard.js

Edit the UserDashboard.js to look as follows:

编辑UserDashboard.js以使其如下所示:

// src/Users/UsersDashboard.js    import React from 'react';    import {
Route } from 'react-router-dom'; import UsersList from './UsersList'; import UsersDetails from './UsersDetails'; const UsersDashboard = ({
users, user, match }) => (
(
user.id === parseInt(props.match.params.id, 10) )[0] } match={
match} /> )} />
); export default UsersDashboard;

In the above, we used the Route component provided by react-router-dom as a component to display the specific user detail when the card is clicked.

在上面,我们使用了react-router-dom提供的Route组件作为单击卡时显示特定用户详细信息的组件。

Now, lets put this all together. Update the src/App.js file to look as follows:

现在,让所有这些放在一起。 更新src/App.js文件,如下所示:

// src/App.js    import React, {
Component } from 'react'; import {
Route, Redirect } from 'react-router-dom'; import Nav from './Nav'; import UsersList from './Users/UsersList'; import UsersDetails from './Users/UsersDetails'; import UsersDashboard from './Users/UsersDashboard'; import './App.css'; class App extends Component {
state = {
users: [ {
id: 39191, avatar: 'https://avatars0.githubusercontent.com/u/39191?v=4', name: 'Paul Irish', username: 'paulirish', followers: '12k', following: '1k', repos: '1.5k' }, //... other user data ] }; render() {
return (
(
)} />
); } } export default App;

When we go back to the browser, we get the following:

当我们回到浏览器时,得到以下信息:

Users Dashboard

Users Details

Note the difference in the URL when the user details are displayed

注意显示用户详细信息时URL的不同

( )

Here’s where it all gets interesting, when users visit this application, no matter the screen size, they get this same view and functionality. In full-blown applications, it’s good to give the users experiences they can enjoy properly and one way to do that is to serve them views that match their exact device sizes. We are now going to take a look at how to do this in our application.

有趣的是,当用户访问此应用程序时,无论屏幕大小如何,他们都将获得相同的视图和功能。 在功能完善的应用程序中,最好为用户提供他们可以正确享受的体验,而做到这一点的一种方法是为他们提供与其确切的设备尺寸相匹配的视图。 现在,我们将看看如何在我们的应用程序中执行此操作。

When visiting the application on a wide screen, the user is redirected to the /dashboard route of the application and when viewing on a smaller screen, the user should be directed to the /users route of the application. Let’s see how to do this.

在宽屏幕上访问应用程序时,用户将被重定向到应用程序的/dashboard路线,而在较小屏幕上查看时,应将用户定向到应用程序的/users路线。 让我们看看如何做到这一点。

Update the src/App.js file to look like this:

更新src/App.js文件,如下所示:

// src/App.js    import React, {
Component } from 'react'; import {
Route, Switch, Redirect } from 'react-router-dom'; import Media from 'react-media'; import Nav from './Nav'; import UsersList from './Users/UsersList'; import UsersDetails from './Users/UsersDetails'; import UsersDashboard from './Users/UsersDashboard'; import './App.css'; class App extends Component {
//set application state [...] render() {
return (
{
matches => matches ? (
(
)} />
(
user.id === parseInt(props.match.params.id, 10) )[0] } { ...props} /> )} />
) [...]

In the snippet above, we use the Media component to check the size of the screen. If the screen width is less than 599px, we set the set what we want to be displayed for different routes and also redirect the / and /dashboard routes to the /users route.

在上面的代码段中,我们使用Media组件检查屏幕的大小。 如果屏幕宽度小于599像素,则设置要设置为不同路线显示的内容,并将//dashboard路线重定向到/users路线。

Now, if the screen size is greater than 599px we go ahead to display the full user dashboard as we did earlier

现在,如果屏幕尺寸大于599px我们将像之前一样继续显示完整的用户仪表板

// src/App.js                [...]                : (                  
(
)} />
) } ); } } export default App;

Now, when we visit our application, our app works like this:

现在,当我们访问应用程序时,我们的应用程序的工作方式如下:

Responsive Routing Demo

At this point, we can see that is a lot better to serve different routes based on screen sizes than using just media queries because you can now serve specially designed components to users based on their device sizes.

在这一点上,我们可以看到,基于屏幕大小提供不同的路由比仅使用媒体查询要好得多,因为您现在可以根据用户的设备大小为他们提供专门设计的组件。

( )

In this article, we saw an introduction to component-based routing with React and how to implement conditional rendering in your React applications. Here’s a link to the full repository. Feel free to leave a comment or suggestion below

在本文中,我们看到了使用React进行基于组件的路由的介绍,以及如何在React应用程序中实现条件渲染。 这是完整存储库的链接。 随时在下面发表评论或建议

翻译自:

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

你可能感兴趣的文章
java 多线程的应用场景
查看>>
dell support
查看>>
转:Maven项目编译后classes文件中没有dao的xml文件以及没有resources中的配置文件的问题解决...
查看>>
解决“Eclipse中启动Tomcat后,http://localhost:8080/无法访问”的问题
查看>>
LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
查看>>
百度杯WriteUp
查看>>
test
查看>>
系统日志2-日志查询
查看>>
作用域和 DOM
查看>>
P1280 尼克的任务
查看>>
jemter --分布式部署测试
查看>>
CSS属性选择符
查看>>
Open Source Streaming Server--EasyDarwin
查看>>
【面试题】比给定数大的最小数
查看>>
什么是PHP无限级分类
查看>>
Git的使用--如何将本地项目上传到Github
查看>>
【7.0】操作excel
查看>>
Linux命令行安装Oracle12c
查看>>
LeetCode 第136题 只出现了一次的元素
查看>>
学习笔记-php图像简单完美剪裁-2016.4.7
查看>>