Home > Web Front-end > JS Tutorial > body text

Detailed explanation of steps to use React-router v4

php中世界最好的语言
Release: 2018-05-24 10:55:41
Original
1878 people have browsed it

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
Copy after login

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<Route> 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

如:
使用组件:

<Route exact path="/" component={HomePage} />
Copy after login

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

<Route path="/" render={()=><p>HomePage</p>} />
Copy after login

来看哥更复杂的:

const FadingRoute = ({ component, ...rest }) => (
  <Route {...rest} render={(props) => (
    <FadeIn>
      <componnet {...props} />
    </FadeIn>
  )} />
)
<FadingRoute path="/cool" component={Something} />
Copy after login

使用children

<ul>
  <ListItemLink to="/somewhere" />
  <LinkItemLink to="/somewhere-else" />
</ul>
const ListItemLink = ({to, ...rest}) => (
  <Route path={to} children={({math}) => (
    <li className={match ? &#39;active&#39; : &#39;&#39;}>
      <Link to={to} {...rest} />
    </li>
  )} />
)
Copy after login

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

URL / Path / Route的参数

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

<Route path="/:param1" component={HomePage} />
const HomePage = ({match}) => (
  <p>
    <h1> parameter => {match.params.param1}
  </p>
);
Copy after login

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

  • url: 匹配的url。

  • path:就是path。

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

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

理解并使用Link

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

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

import { Link } from 'react-router-dom';
const Nav = () => (
  <Link to &#39;/&#39;>Home</Link>
);
Copy after login

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

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

<Link to{{
  pathname: &#39;/me&#39;,
  search: &#39;?sort=asc&#39;,
  hash: &#39;#hash&#39;,
  state: { fromHome: true }
}} />
Copy after login

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

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

<NavLink to="/me" activeStyle={{SomeStyle}} activeClassName="selected">
  My Profile
</NavLink>
Copy after login

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

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

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

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

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

const BaseLayout = () => (
  <p className="base">
    <header>
      <p>React Router v4 Browser Example</p>
      <nav>
        <ul>
          <li><Link ="/">Home</Link></li>
          <li><Link ="/about">About</Link></li>
          <li><Link ="/me">Profile</Link></li>
          <li><Link ="/login">Login</Link></li>
          <li><Link ="/register">Register</Link></li>
          <li><Link ="/contact">Contact</Link></li>
        </ul>
      </nav>
    </header>
    <p className="container">
      <Route path="/" exact component={HomePage} />
      <Route path="/about" component={AboutPage} />
      <Route path="/contact" component={ContactPage} />
      <Route path="/login" component={LoginPage} />
      <Route path="/register" component={RegisterPage} />
      <Route path="/me" component={ProfilePage} />
    </p>
    <footer>
      React Router v4 Browser Example (c) 2017
    </footer>
  </p>
);
Copy after login

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

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>
Copy after login

最后,写App组件。

const App = () => (
  <BrowserRouter>
    <BaseLayout />
  </BrowserRouter>
)
render(<App />, document.getElementById('root'));
Copy after login

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

理解和使用非排他的路由

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

<Route path="/" exact component={HomePage} />
Copy after login

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

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

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

const BaseLayout = () =>  (
  <p className="base">
    <header>
      <p>React Router v4 Browser Example</p>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li>
            <Link to="/me">Profile</Link>
            <Route path="/me" component={ProfileMenu} />
          </li>
          {/*略*/}
        </ul>
      </nav>
    </header>
  </p>
);
Copy after login

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

理解排他路由

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

import { Switch, Route } from 'react-router';

  <Route exact path="/" component={HomePage} />
  
  
  
Copy after login

浏览器历史

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

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

history.push("/my-path")
history.replace("/my-path")
Copy after login

用另外的方法可以写成:

<Link to="/my-path" />
<Redirect to="my-path" />
Copy after login

使用<Redirect>组件实现重定向

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

<Redirect to {{
  pathname: &#39;/register&#39;,
  search: &#39;?utm=something&#39;,
  state: { referrer: someplage.com }
}}>
Copy after login

或者,更为简单的:

<Redirect to="register" />
Copy after login

最后

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!