Preliminary study on React Router 4.0

Source: Internet
Author: User


React Router 4.0 (hereinafter referred to as RR4) has been officially released, it follows the react design concept that everything is a component. So RR4 is just a bunch of components that provide navigation (and a number of objects and methods), with a declarative (in-use), and a combination of features. http://www.jianshu.com/p/e3adc9b5f75c



RR4 this time using a single Code warehouse model architecture (MONOREPO), which means that there are several separate packages in this warehouse, respectively: React-router react router core react-router-dom for DOM binding react Route R react-router-native Integrated router static route matching for react React-router-redux react Router redux and react-router-config for react native Little Helper.



This article mainly discusses how to use RR4 in Web apps. Reference React-router or React-router-dom.



In the use of react, we usually introduce two packages, react and react-dom, then React-router and React-router-dom are not two to be quoted.
No, the pit is right here. The two of them simply cite one, and the difference is that the latter has a DOM-class component like <Link> <BrowserRouter>.
So we just need to refer to the React-router-dom package. Of course, if paired with Redux, you need to use React-router-redux.
What is the diff between React-router-dom & React-router? Component <BrowserRouter>



A Gao Jie Lu that uses the HTML5 history API ensures that your UI interface and URLs are synchronized. This component has the following properties:



Basename:string
Role: Add a base URL for all locations
Usage Scenario: If you need to deploy the page to the server level two directory, you can use basename to set it up to this directory.


<browserrouter basename= "/minooo"/> <link to= "/react"/>
//FINAL render <a href= "/minooo/react" >


Getuserconfirmation:func
Role: Navigate to the function that is executed before this page by default using Window.confirm
Usage Scenario: Available when a user is required to enter a page, but not often.


Const GETCONFIRMATION = (message, callback) => {
  Const allowtransition = window.confirm (message)
  callback ( allowtransition)
}

<browserrouter getuserconfirmation={getconfirmation (' Are you sure? ', yourcallback)}/ >


Forcerefresh:bool
Role: Forces a refresh of the page when the browser does not support the HTML5 history API.
Usage scene: Ditto.


Const Supportshistory = ' pushstate ' in Window.history
<browserrouter forcerefresh={!supportshistory}/>


Keylength:number
Function: Set the length of the Location.key in which it is routed. The default is 6. (Key role: Click on the same link, each time the route under the Location.key will change, you can change the key to refresh the page. )
Usage scenarios: On-demand settings.


<browserrouter keylength={12}/>


Children:node
Function: Renders unique child elements.
Use scenario: As a REAC T component, born with children attribute.



Try <HashRouter>



Hash history does not support Location.key and location.state. Also, since the technology is only used to support older browsers, it is more recommended that you use Browserrouter, which no longer makes redundant introductions. <Route>



<Route> may be the most important component of RR4, and it is important that you understand it, learn it, and use it well. Its most basic responsibility is to render the corresponding UI interface when the access address of the page matches the path on the Route.



<Route> with three Render method and three props.



Render methods were: <route component> <route render> <route children>
Each render method has a different scenario, the same <Route> should use only one render method, and in most cases you will use component.



Props are: match location history
All Render method will be passed into these props without exception.



Component
A react component is rendered only when the access address and Route match, at which point the component accepts route props (match, location, history).
When using component, Router will use React.createelement to create a new react element based on the given component. This means that if you use inline functions (inline function) to pass values to component, you will create unnecessary duplicate loads. For inline rendering (inline rendering), it is recommended that renderprop be used.


<Route path = "/ user /: username" component = {User} />
const User = ({match}) => {
  return <h1> Hello {match.params.username}! </ h1>
}
render: func
This method is suitable for inline rendering and does not cause the duplicate loading problem mentioned above.

// Inline rendering
<Route path = "/ home" render = {() => <h1> Home </ h1} />

// packaging combination
const FadingRoute = ((component: Component, ... rest)) => (
  <Route {... rest} render = {props => (
    <FadeIn>
      <Component {... props} />
    </ FaseIn>
  )} />
)

<FadingRoute path = "/ cool" component = {Something} />
children: func
Sometimes you just want to know if the visit address is matched and change something else, not just the corresponding page.

<ul>
  <ListItemLink to = "/ somewhere" />
  <ListItemLink to = "/ somewhere-ele" />
</ ul>

const ListItemLink = ((to, ... rest)) => (
  <Route path = (to} children = (({match}) => (
    <li className = (match? 'active': '')>
      <Link to = {to} {... rest} />
    </ li>
  )}
)
path: string
Any valid URL path that can be resolved by path-to-regexp

<Route path = "/ users /: id" component = {User} />
If path is not given, then the route will always match.

exact: bool
If true, routes with path '/ one' will not match '/ one / two' and vice versa.

strict: bool
Match to the trailing slash at the end of the path. If true. A path of '/ one /' will not match '/ one' but will match '/ one / two'.

If you want to ensure that the route has no trailing slash, then strict and
both must be true at the same time

Try <Link>

Provide declarative, accessible navigation for your application.

to: string
Role: Jump to the specified path
Use case: If it is just a simple jump, use the path in the form of a string directly.

<Link to = "/ courses" />
to: object
Role: Jump to specified path with parameters
Scenario: For example, the page that you click on the link to be redirected needs to display the content corresponding to the link, or this is a payment redirect, and information such as the price of the product needs to be passed.

<Link to = {{
  pathname: '/ course',
  search: '? sort = name',
  state: {price: 18}
}} />
replace: bool
When true, after clicking the link, the last address will be replaced with the new address. What does it mean, for example: you visit the four addresses' / one ', / two', / three ', / four' in order, Rolling back will go back to '/ three' '/ two' '/ one', which is in line with our expectations, if we set the replace in the link '/ three' to true. What happens when you click one two three four in turn and then back again. Will go back to '/ three' and '/ one' in turn. I did an online demo for this, you can debug and experience it!

In addition, you can think of what the purpose of this prop is. Some people say that they will be used when using routing as a tab. Welcome comments and discussions.

Try <NavLink>

This is a special version of <Link>, as the name suggests, this is for page navigation. Because navigation needs to be "active".

activeClassName: string
Select the style name to be applied when the navigation is activated. The default style name is active.

<NavLink
  to = "/ about"
  activeClassName = "selected"
> MyBlog </ NavLink>
activeStyle: object
If you don't want to use the style name, write style directly

<NavLink
  to = "/ about"
  activeStyle = {{color: 'green', fontWeight: 'bold'}}
> MyBlog </ NavLink>
exact: bool
If true, the activation style will only be applied when the access addresses match exactly

strict: bool
If true, the activation style will only be applied when the access address suffix slash exactly matches (with or without)

isActive: func
Decide if navigation is active, or do something else while the navigation is active. In any case, it cannot determine whether the corresponding page can be rendered.

Try <Switch>

Only the first <Route> or <Redirect> that matches the current access address is rendered.

Consider the following code. If you visit / about, the components About User Nomatch will be rendered, because their corresponding routes match the visited address / about. This is obviously not what we want, we just want to render the first matching route, so <Switch> came into being.

<Route path = "/ about" component = {About} />
<Route path = "/: user" component = {User} />
<Route component = {NoMatch} />
Maybe you will ask, why doesn't the RR4 mechanism match the first one by default? A: This design allows us to combine multiple <Route> into the application, such as sidebars, breadcrumbs, etc Wait.

In addition, <Switch> is also very suitable for transition animations, because the rendered route is at the same node position as the previously rendered route.

<Fade>
  <Switch>
    {/ * Switch is used. Here only one route is matched at a time, all have only one node. * /}
    <Route />
    <Route />
  </ Switch>
</ Fade>

<Fade>
  <Route />

Related Article

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.