在5分钟内学习React Router-入门教程

Sometimes you've only got 5 minutes to spare. Instead of wasting it on social media, let's get a 5-minute introduction to React-Router! In this tutorial, we're going to learn the basics of routing in React by building navigation for a Scrimba knitting shop website. It's not real, but maybe one day... ;)

有时您只有5分钟的空闲时间。 与其在社交媒体上浪费时间,不如让我们花5分钟时间介绍一下React-Router! 在本教程中,我们将通过为Scrimba针织店网站构建导航来学习React中路由的基础知识。 这不是真实的,但也许有一天...;)

If you want a proper introduction to this subject, you can join the waitlist for my upcoming advanced React course, or if you're still a beginner, check out my introductory course on React.

如果您想对该主题进行适当的介绍,可以加入我即将举行的高级React课程的候补名单,或者如果您仍然是初学者,请查看我的React入门课程。

无论如何,什么是React-Router? (What is React-Router, anyway?)

Many modern websites are actually made up of a single page, they just look like multiple pages because they contain components which render like separate pages. These are usually referred to as SPAs - single-page applications. At its core, what React Router does is conditionally render certain components to display depending on the route being used in the URL (/ for the home page, /about for the about page, etc.).

许多现代网站实际上是由一个页面组成的,它们看起来就像是多个页面,因为它们包含呈现为单独页面的组件。 这些通常被称作水疗- S ingle- p 年龄 pplications。 从根本上讲,React Router的作用是根据URL中使用的路由有条件地呈现某些组件以显示( /表示主页, /about表示关于页面等)。

For example, we can use React Router to connect www.knit-with-scrimba.com/ to www.knit-with-scrimba.com/about or www.knit-with-scrimba.com/shop

例如,我们可以使用React Router将www.knit-with-scrimba.com/连接到www.knit-with-scrimba.com/aboutwww.knit-with-scrimba.com/shop

听起来不错-如何使用? (Sounds great - how do I use it?)

To use React Router, you first have to install it using NPM:

要使用React Router,首先必须使用NPM安装它:

npm install react-router-dom

Alternatively, you can just use this playground in Scrimba, which has the completed code already written.

或者,您可以仅使用Scrimba的操场,该操场已经编写了完整的代码。

You'll need to import BrowserRouter, Route, and Switch from react-router-dom package:

您需要从react-router-dom包中导入BrowserRouter,Route和Switch:

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

In my example, I link the landing page with two other "pages" (which are actually just components) called Shop and About.

在我的示例中,我将着陆页与另外两个称为ShopAbout “页面”(实际上只是组件)链接起来。

First, you'll need to set up your app to work with React Router. Everything that gets rendered will need to go inside the <BrowserRouter> element, so wrap your App in those first. It's the component that does all the logic of displaying various components that you provide it with.

首先,您需要设置您的应用程序以与React Router一起使用。 呈现的所有内容都需要放入<BrowserRouter>元素内,因此<BrowserRouter>将您的App包装在其中。 该组件执行显示您提供的各种组件的所有逻辑。

// index.js
ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>, 
    document.getElementById('root')
)

Next, in your App component, add the Switch element (open and closing tags). These ensure that only one component is rendered at a time. If we don't use this, we can default to the Error component, which we're going to write later.

接下来,在您的App组件中,添加Switch元素(打开和关闭标签)。 这些确保每次仅渲染一个组件。 如果我们不使用它,我们可以默认使用Error组件,稍后再编写。

function App() {
    return (
        <main>
            <Switch>
                
            </Switch>
        </main>
    )
}

It's now time to add your <Route> tags. These are the links between the components and should be placed inside the <Switch> tags.

现在该添加您的<Route>标记。 这些是组件之间的链接,应放置在<Switch>标记内。

To tell the <Route> tags which component to load, simply add a path attribute and the name of the component you want to load with component attribute.

说句<Route>标签,其组件来加载,只需添加一个path属性,并且要与加载组件的名称component的属性。

<Route path='/' component={Home} />

Many homepage URLs are the site name followed by "/", for example, www.knit-with-scrimba.com/. In this case, we add exact to the Route tag. This is because the other URLs also contain "/", so if we don't tell the app that it needs to look for just /, it loads the first one to match the route, and we get a pretty tricky bug to deal with.

许多主页URL是站点名称,后跟"/" ,例如www.knit-with-scrimba.com/ 。 在这种情况下,我们将exact添加到Route标签。 这是因为其他URL也包含“ /”,所以如果我们不告诉应用程序它只需要查找/ ,它将加载第一个以匹配该路由的URL,并且会遇到一个非常棘手的错误。

function App() {
    return (
        <main>
            <Switch>
                <Route path="/" component={Home} exact />
                <Route path="/about" component={About} />
                <Route path="/shop" component={Shop} />
            </Switch>
        </main>
    )
}

Now import the components into the app. You may wish to have them in a separate "components" folder to keep code clean and readable.

现在将组件导入到应用程序中。 您可能希望将它们放在单独的“ components”文件夹中,以保持代码的清洁和可读性。

import Home from './components/Home';
import About from './components/About';
import Shop from './components/Shop';

Onto that error message I mentioned earlier, which loads if a user types an incorrect URL. This is just like a normal <Route> tag, but with no path. The Error component contains <h1>Oops! Page not found!</h1>. Don't forget to import it into the app.

关于我之前提到的错误消息,如果用户键入了错误的URL,则会加载该错误消息。 这就像普通的<Route>标记,但没有路径。 错误组件包含<h1>Oops! Page not found!</h1> <h1>Oops! Page not found!</h1> 。 不要忘记将其导入到应用程序中。

function App() {
    return (
        <main>
            <Switch>
                <Route path="/" component={Home} exact />
                <Route path="/about" component={About} />
                <Route path="/shop" component={Shop} />
                <Route component={Error} />
            </Switch>
        </main>
    )
}

So far, our site is only navigable by typing the URLs. To add clickable links to the site, we use the Link element from React Router and set up a new Navbar component. Once again, don't forget to import the new component into the app.

到目前为止,我们的网站只能通过输入URL进行导航。 为了向网站添加可点击的链接,我们使用了React Router中的Link元素并设置了一个新的Navbar组件。 再一次,不要忘记将新组件导入到应用程序中。

Now add a Link for each component in the app and use to="URL" to link them.

现在,为应用程序中的每个组件添加一个Link ,并使用to="URL"进行链接。

function Navbar() {
  return (
    <div>
      <Link to="/">Home </Link>
      <Link to="/about">About Us </Link>
      <Link to="/shop">Shop Now </Link>
    </div>
  );
};

Your site now has clickable links that can navigate you around your single-page app!

您的网站现在具有可单击的链接,可以在单页应用程序中导航!

结论 (Conclusion)

So there we have it. If you want to easily navigate around a React app, forget the anchor tags and add React Router. It's clean, it's organized, and it makes adding and deleting pages a whole lot easier.

因此,我们有它。 如果您想轻松地在React应用程序中导航,请忘记锚标记并添加React Router。 它很干净,井井有条,并且使添加和删除页面变得更加容易。

To learn more about React Hooks and other great features of React, you can join the waitlist for my upcoming advanced React course.

要了解有关React Hooks和React其他重要功能的更多信息,可以加入我即将举行的高级React课程的候补名单

Or if you're looking for something more beginner friendly, you can check out my introductory course on React.

或者,如果您正在寻找更适合初学者的内容,则可以查看我关于React的入门课程。

Happy coding ;)

快乐的编码;)

翻译自: https://www.freecodecamp.org/news/react-router-in-5-minutes/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值