[Web Front end] React Router v4 into the Pit guide

Source: Internet
Author: User

CP from:https://www.jianshu.com/p/6a45e2dfc9d9

The root of all evil

From React Router V4 officially released also has been in the past three months, this week to upgrade a react shelf, before the route with the v2.7.0 version, so decided to upgrade the route, just "Taste fresh" ...

Rumors, the current official maintenance of 2.x and 4.x two versions. (ヾ? ﹏?)?? Yi, now believe that wit like mine you also will find, Reactrouter v3 go where? Lost the whole?? Shambhala out of the pot??? Dare not give me a perfect explanation!? In fact, the 3.x version did not introduce any new features compared to 2.x, but removed the warning of some deprecated APIs from the 2.x version. According to the plan, a new project with no historical baggage to use the stable version of Reactrouter should use Reactrouter 3.x. Currently the 3.x version is also in beta, but it will be released before the 4.x release. If you are already using the 2.x version, then the upgrade 3.x will not have any additional code changes.

React Router v4.jpg Under the introduction of politeness

React Router V4 compared to the previous three versions have fundamental changes, the first is to follow the Just Component API design concept, followed by a lot of API simplification, for beginners to reduce the learning difficulty, but if it is the reconstruction of the previous project, um, there is no * * can be said. The main features of this upgrade are as follows:

  • Declarative (declarative)
  • Can be combined (composability)

React Router V4 follows React's philosophy: All things are components . So the upgrade of the Route, Link, switch, etc. are a common component.

React Router V4 manages multiple Repository based on Lerna. This code base includes:

  • React-router React Router Core
  • React-router-dom react Router for DOM binding
  • React-router-native react router for react native
  • Integration of React-router-redux react router and redux
  • React-router-config Static routing configuration Help assistant
Plug-in first introduction

Usually we in the use of React, generally to introduce two packets, react and react-dom , then react-router and is react-router-dom not two to be quoted? Note that the high energy ahead, the first pit of entry is here . The two of them just have to quote one, and the difference is that the latter is more <Link> <BrowserRouter> of a DOM class component than the former. So we just have to quote react-router-dom This package to be OK. Of course, if redux you match, you need to use it react-router-redux .

Introduction to main components <Router>

In the API versions prior to 4.0, <Router> the children of a component could only be a variety of components provided by React Router, such as <Route>、<IndexRoute>、<Redirect> . In React Router 4, you can put a variety of components and tags into the <Router> assembly, and his role is more like Redux <Provider> . The difference is <Provider> to keep the update with the store, and <Router> to keep it in sync with the location. examples are as follows:

// 示例1
<Router>    <div>      <ul>        <li><link to= "/" > Home </Link></li>        <li><link to= "/about" > About </Link></li>        <li><link to= "/topics" > Topic list </Link></li>      </ul>      

Router is the underlying interface that is common to all routing components, and in general our application does not use this interface, but rather uses advanced routing:

  • <BrowserRouter>: Use the history API provided by HTML5 to keep the UI and URL synchronized;
  • <HashRouter>: Use URL hash (for example: Window.location.hash) to maintain UI and URL synchronization;
  • <MemoryRouter>: Can save your "URL" history in memory (not read and write to the address bar);
  • <NativeRouter>: Provides routing support for the use of react native;
  • <StaticRouter>: Never change the address;

TIPS: The second pit, unlike the previous router, where <Router> only one child element is allowed under the component, if there are more than one, an error will be found.

The opposite is typical here:

// 示例2
<Router>      <ul>        <li><link to= "/" > Home </Link></li>        <li>< Link to= "/about" > About </Link></li>        <li><link to= "/topics" > Topic list </link></li >      </ul>      

Yes, example 2 without the <div> protection of the father, will report the following exception information:

Error.jpg

<Route>

We know that the main function of the route component is to render some UI when a location matches the path of the route. Examples are as follows:

<Router>  <div>    <route exact path= "/" component={home}/>    <route path= "/news" component={newsfeed}/>  </div></Router>//  If the address of the app is/, then the corresponding UI will look like this:<div >  <Home/></div>//  If the address of the app is/news, then the corresponding UI will look like this:<div>  < Newsfeed/></div>

<Route>The component has the following properties:

  • Path (String): Route matching path. (The route without the path attribute will always match);
  • Exact (BOOL): When True, requires that the path and location.pathname must match exactly;
  • Strict (BOOL): True, the path with the trailing slash can only match the location.pathname with the slash;

Again, there are two vivid examples:

Exact configuration:

Path Location.pathname Exact is matched
/one /one/two True Whether
/one /one/two False Is

Strict configuration:

Path Location.pathname Strict is matched
/one/ /one True Whether
/one/ /one/ True Is
/one/ /one/two True Is

At the same time, the new version of the route <Route> provides three ways to render content:

  • <Route component>: The react component will be rendered when the address matches, and the route props will be rendered along with it;
  • <Route render>: This method is especially convenient for inline rendering and packaging components without causing unexpected re-mounting;
  • <Route children>: The same way that the Render property works, except that it is called regardless of whether the address matches or not;

The first way there is nothing to say, as before, here we focus on <Route render> the way of rendering:

// in-line rendering example <route path= "/Home" render={() = <div>Home</div>}/>//  packaging/Crafting Const Fadingroute = ({component:component, ... rest})  = = (<route {... rest} render={props =>
   
     (    <FadeIn>      <component {...props}/>    </FadeIn>  )}/>
    ) <fadingroute path= "/cool" component={something}/>
   

TIPS: the third pit! <Route component>the priority is <Route render> higher, so do not use both properties in the same <Route> .

<Link>

Not much different from previous versions, focus on component properties:

  • to (String/object): The path or address to jump;
  • Replace (BOOL): True , when the link is clicked, the original address in the access history is replaced with the new address, and a new record is added to the original access history when the link is clicked. The default is False;

Examples are as follows:

// Link Component Example // to string<link to= "/about" > About </Link>//  to obj<link to={{  ' /courses ',  '? Sort=name ',  ' #the-hash ',  true  }}} />//<link to= "/courses" replace/>

<NavLink>

<NavLink>is <Link> a specific version that will add style parameters to the already rendered element when matching the current URL, component properties:

  • Activeclassname (String): Sets the selected style, the default value is active;
  • Activestyle (object): Adds a style to this element when the element is selected;
  • Exact (BOOL): True when the address exactly matches the class and style to be applied;
  • Strict (BOOL): When True, the slash after position pathname is considered when determining if the location matches the current URL;
  • IsActive (func): The ability to determine the additional logic that links are activated;

From here we can also see that the new version of the route on the component is indeed a lot of effort, to see the use of NavLink example:

//activeclassname style is selected when selected<NavLink to= "/faq"Activeclassname= "Selected" >FAQs</NavLink>//style settings for style activestyle when checked<NavLink to= "/faq"Activestyle={{fontweight:' Bold ', Color:' Red '   }}>FAQs</NavLink>//activates the link when the event ID is oddConst Oddevent = (match, location) = = {  if(!match) {    return false} const EventID=parseint (Match.params.eventID)return!isnan (EventID) && EventID% 2 = = 1}<NavLink to= "/events/123"isActive={oddevent}>event 123</navlink>

<Switch>

This component is used to render the first or the matching address <Route> <Redirect> . So what's the difference between it and using a bunch of route?

<Switch>The uniqueness of this is that it only renders a single route. Conversely, each containing a matching address (location) <Route> will be rendered. Consider the following code:

<route path= "/about" Component={about}/><route path= "/:user" Component={user}/><route component={ Nomatch}/>

If the URLs are now, then, and all /about <About> <User> <NoMatch> will be rendered, because they all match the path. This design allows us to <Route> combine multiple combinations into our applications in a variety of ways, such as sidebar (sidebars), breadcrumbs (breadcrumbs), bootstrap tabs and more. However, occasionally we just want to choose one <Route> to render. If we are now in /about , we do not want to match /:user (or display our "404" page). Here's how to use Switch:

<Switch>  <route exact path= "/" component={home}/>  <route path= "/about" component={about}/ >  <route path= "/:user" component={user}/>  <route component={nomatch}/></switch>

Now, if we're in /about , we <Switch> 'll start looking for a match <Route> . <Route path="/about"/>will be matched and <Switch> will stop looking for a match and render <About> . Again, if we are in /michael , it <User> will be rendered.

Above is my react Router v4 of the preliminary examination, anyway, is also on the side of the document, while testing water, if there are errors or omissions, but also please understand and do not hesitate to correct me!



Longan _noble
Links: https://www.jianshu.com/p/6a45e2dfc9d9
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

[Web Front end] React Router v4 into the Pit guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.