search
HomeWeb Front-endJS TutorialDetailed explanation of steps to use React-router v4

Detailed explanation of steps to use React-router v4

May 24, 2018 am 10:55 AM
react-routeruseDetailed explanation

This time I will bring you a detailed explanation of the steps to use React-router v4. What are the precautions when using React-router v4? The following is a practical case, let’s take a look.

Perhaps the best way to learn react-router is to use react-router-dom v4 to write a multi-page react application. This react application will include login, registration, homepage, contact and other pages. But first let's take a look at the concept of react router v4 and how it differs from v3.

React router v4 vs v3

v4 is a rewrite of react router, so it has many differences from v3. The main ones are:

  • In react router v4, routing is no longer centralized. It becomes part of the application layout and UI.

  • The router used by the browser is in react-router-dom. Therefore, when using it in the browser, you only need to import react-router-dom.

  • New concepts BrowerRouter and HashRouter. They each serve different situations. See below for details.

  • No longer use {props.children} to handle nested routes.

  • v4 routing is no longer exclusive by default and will have multiple matches. v3 is exclusive by default, and only one match will be used.

react-router-dom is used in react-router for browsers. react-router is divided into the following parts:

  • react-router is a common part for browsers and native applications.

  • react-router-dom is for browsers.

  • react-router-native is for native applications.

React-router vs react-router-dom vs react-router-native

react-router is the core part. react-router-dom Provides customized components required for browser use. react-router-native specifically provides the parts that need to be used in native mobile applications. Therefore, if you implement browser development in this example, you only need to install react-router-dom.

Installation

As mentioned above, we use react to develop web applications, so we only need to install react-router-dom.

  npm install react-router-dom --save

Understand and use react-router

  • BrowserRouter, which is the implementation of the Router interface. Make the page and browser history consistent. For example: window.location.

  • HashRouter is the same as above, except that it uses the hash part of the url, such as: window.location.hash.

  • MemoryRouter,

  • ##NativeRouter, handle routing in react native.

  • Static<a href="http://www.php.cn/wiki/188.html" target="_blank">Router</a>, handles static routing, the same as v3.

BrowserRouter vs HashRouter

Among the various routers of react-router,

and can be used in the browser. If you are using a non-static site and want to handle various URLs, then you need to use BrowserRouter. On the contrary, if your server only handles static URLs, use HashRouter.

Understanding and using Route

The component is the most useful component in react router v4. The usage philosophy behind it is also very simple. Whenever you need to draw a component when matching a certain path, you can use the

Route component.

Route component can use the following attributes:

  • path attribute,

    string type, its value is to match the url.

  • component attribute, its value is a component. This component will be drawn after

    path is successfully matched.

  • exact attribute, this attribute is used to indicate whether this route is an exclusive match.

  • strict attribute, this attribute specifies that the path only matches paths ending with a slash.

还有其他的一些属性,可以用来代替component属性。

  • render属性,一个返回React组件的方法。传说中的rencer-prop就是从这里来的。

  • children属性,返回一个React组件的方法。只不过这个总是会绘制,即使没有匹配的路径的时候。

多数的时候是用component属性就可以满足。但是,某些情况下你不得不使用renderchildren属性。

  • match

  • location

  • history

如:
使用组件:

&lt;route&gt;&lt;/route&gt;

使用render属性实现内联绘制:

<route><p>HomePage</p>} /></route>

来看哥更复杂的:

const FadingRoute = ({ component, ...rest }) => (
  <route> (
    <fadein>
      <componnet></componnet>
    </fadein>
  )} />
)
<fadingroute></fadingroute></route>

使用children


         
const ListItemLink = ({to, ...rest}) => (    (     
  •       <link>     
  •   )} /> )

    更多关于react-router v4如何匹配路径的内容,请移步这里。

    URL / Path / Route的参数

    通常情况下,我们都会在路径里添加参数。这样方便在不同的组件之间传递一些必要的数据。那么我们如何才能获取到这些传递的参数,并传递给组件中呢?我们只需要在路径的最后加上/:param。如:

    &lt;route&gt;&lt;/route&gt;
    const HomePage = ({match}) => (
      

        

     parameter => {match.params.param1}    );

    一旦有路径可以匹配成功,那么就会穿件一个拥有如下属性的对象,并传入绘制的组件里:

    • url: 匹配的url。

    • path:就是path。

    • isExact:如果path和当前的widnow.location的path部分完全相同的话。

    • params:在URL里包含的参数。

    Link是react router v4特有的一个组件。是用来代替上一版的anchor link。使用Link可以在React应用的不同页面之间跳转。与unclor会重新加载整个页面不同,Link只会重新加载页面里和当前url可以匹配的部分。

    Link组件需要用到to属性,这个属性的值就是react router要跳转到的地址。如:

    import { Link } from 'react-router-dom';
    const Nav = () => (
      <link>Home
    );

    当被点击的时候,会跳转到路径:/

    to属性的值可以是一个字符串,也可以是一个location(pathname, hash, state和search)对象。比如:

    <link>

    Link也可以使用replace属性,如果点击的话,那么history里的当前领会被replace。

    <link>和

    NavLinkLink的一个子类,在Link组件的基础上增加了绘制组件的样式,比如:

    <navlink>
      My Profile
    </navlink>

    使用react router dom实现你的第一个demo

    现在我们用react router dom来实现第一个demo。

    首先,引入必要的组件。比如:RouteBrowserRouter

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

    接下来,我们创建一些组件和一些Html标签。同时我们用react router v4里的LinkNavLink组件。

    const BaseLayout = () => (
      

        

          

    React Router v4 Browser Example

               
        

          &lt;route&gt;&lt;/route&gt;       &lt;route&gt;&lt;/route&gt;       &lt;route&gt;&lt;/route&gt;       &lt;route&gt;&lt;/route&gt;       &lt;route&gt;&lt;/route&gt;       &lt;route&gt;&lt;/route&gt;     

        
          React Router v4 Browser Example (c) 2017     
       );

    然后我们来创建需要的组件:

    const HomePage = () => <p>This is a Home Page</p>
    const LoginPage = () => <p>This is a Login Page</p>
    const RegisterPage = () => <p>This is a Register Page</p>
    const ProfilePage = () => <p>This is a Profile Page</p>
    const AboutPage = () => <p>This is a About Page</p>
    const ContactPage = () => <p>This is a Contact Page</p>

    最后,写App组件。

    const App = () => (
      <browserrouter>
        <baselayout></baselayout>
      </browserrouter>
    )
    render(<app></app>, document.getElementById('root'));

    如你所见,react router v4的组件还非常的易用的。

    理解和使用非排他的路由

    在上例中,我们在HomePage组件的路由里使用了属性exact

    &lt;route&gt;&lt;/route&gt;

    这是因为v4中的路由默认都是非排他的,这一点和v3的实现思路截然不同。如果没有exact属性,HomePage组件和其他的组件就会同事绘制在页面上。

    如,当用户点了登录连接以后,"/""/login"都满足匹配条件,对应的登录组件和Home组件就会同时出现在界面上。但是,这不是我们期待的结果,所以我们要给"/"path加上exact属性。

    现在我们来看看非排他的路由有什么优点。假如我们有一个子菜单组件需要显示在profile页面出现的时候也出现。我们可以简单的修改BasicLayout来实现。

    const BaseLayout = () =>  (
      

        

          

    React Router v4 Browser Example

               
      

    );

    这样我们就会看到对应于"/me"路径的组件都绘制出来了。这就是非排他路由的好处。

    理解排他路由

    排他路由是react router v3的默认实现。只有第一个匹配的路由对应的组件会被绘制。这一点也可以用react router v4的Switch组件来实现。在Switch组件中,只有第一个匹配的路由&lt;route&gt;&lt;/route&gt;或者&lt;redirect&gt;&lt;/redirect&gt;会被绘制:

    import { Switch, Route } from 'react-router';
    
      &lt;route&gt;&lt;/route&gt;
      &lt;route&gt;&lt;/route&gt;
      &lt;route&gt;&lt;/route&gt;
      &lt;route&gt;&lt;/route&gt;
    

    浏览器历史

    react router v4中,提供了一个history对象。这个对象包含了多个api,可以用来操作浏览器历史等。

    你也可以在React应用里使用history对象的方法:

    history.push("/my-path")
    history.replace("/my-path")

    用另外的方法可以写成:

    <link>
    &lt;redirect&gt;&lt;/redirect&gt;

    使用组件实现重定向

    无论何时你要重定向到另外一个地址的时候,都可以使用Redirect组件:

    &lt;redirect&gt;&lt;/redirect&gt;

    或者,更为简单的:

    &lt;redirect&gt;&lt;/redirect&gt;

    最后

    react router v4让开发react应用变得更加的简单。让react应用内的页面跳转更加简单。你只需要声明一个BrowserRouter或者HashRouter,然后在它的内部放上一系列的Route组件,这些主键只要包含pathcomponent属性。无论何时有了匹配的路由,那么它就会进行非排他的绘制(所有匹配的路由都会绘制)。你也可以把Route放在Switch组件里来实现排他的绘制(只有第一个匹配的路由会被绘制)。你可以在路径中传递参数,match对象会保留这些参数。最后,所有在web中使用的路由组件都包含在react-router-dom中。只需要引入react-router-dom就可以使用。

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    Chart.js 轻量级HTML5图表绘制工具库使用步骤详解

    Chart.js轻量级图表库使用案例解析

    The above is the detailed content of Detailed explanation of steps to use React-router v4. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

    The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

    I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

    How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

    This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

    JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

    JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)