React Router 4.0 Experience

Router 4.0 React (hereinafter referred to as RR4) has been officially released, it follows the design philosophy React, that all things are components. So RR4 just a bunch of offers components (there are a number of objects and methods) navigation functions , with declarative (in terms of a simple declarative programming is that you only need to worry about what to do, without concern for how to do it, just like you write React assembly only need to render the components you want, as to how the components to achieve is something React to be processed.), the combination of characteristics. ,
The single-RR4 code repository model architecture (monorepo), which means there are a number of the repository independent package, namely:
  • react-router React Router Core
  • react-router-dom React Router DOM bindings for
  • react-router-native React Router for React Native of
  • react-router-redux React Router and integration Redux
  • react-router-config Static routing configuration assistant

Quote

react-router or react-router-dom?

React in use, we generally introduced two packages, react and react-dom then react-router and react-router-dom is not to be quoted two do?
No, pit here. As long as the two of them a reference on the line, the difference is that the latter is more out of <Link> <BrowserRouter> this DOM class components.
So we simply refer to react-router-domthe package on the line. Of course, if with redux, you also need to use react-router-redux .
what is the diff between react-router -dom & react-router?

Package

<BrowserRouter>

Use a high-order routing component HTML5 history API to ensure that your UI interface and the URL to keep pace. This component has the following properties:

basename: string
: Addition of a benchmark for all positions URL
usage scenarios: If you need to deploy to the secondary pages directory server, you can use the basenameset to this directory.

<BrowserRouter basename="/minooo" />
<Link to="/react" /> // 最终渲染为 <a href="/minooo/react">

  

getUserConfirmation: func
function: function navigate to this page before the execution, the default window.confirm
usage scenarios: what is available when the operation is performed before the user needs to enter the page, but generally not much use.

const getConfirmation = (message, callback) => {
  const allowTransition = window.confirm(message)
  callback(allowTransition)
}

 

<BrowserRouter getUserConfirmation={getConfirmation('Are you sure?', yourCallBack)} /> 

  

forceRefresh: bool
effect: When the browser is not supported by history API HTML5 forced refresh the page.
Use Scene: Same as above.

const supportsHistory = 'pushState' in window.history
<BrowserRouter forceRefresh={!supportsHistory} />

keyLength: number
role: it is provided inside the route location.keylength. The default is 6. (The role of key: When you click on a link with a time under the route location.keywill change, can be refreshed by changes in key page.)
Usage scenarios: on-demand setting.

<BrowserRouter keyLength={12} />

children: node
role: Rendering the only child elements.
Be used: as a component Reac t, children born carrying properties.

try it


<HashRouter>

Hash history does not support location.keyand location.state. In addition, as the technology is only used to support older browsers, so the more we recommend the use BrowserRouter, this API will not make unnecessary introduction.


<Route>

<Route> RR4 is perhaps the most important component, it is important to understand that you have it, learn it, use it well. It is the most basic duty is when the path on the access page address Route match, rendering the corresponding UI interface.

<Route> three render method and carrying three props.

render methods are:

  • <Route component>
  • <Route render>
  • <Route children>
    Each render method has different application scenarios, the same <Route>should use only one render method, in most cases you will use component.

props are:

  • match
  • location
  • history
    All, without exception, the render method will be passed these props.

component
only when accessing the address and routing match, a React component will be rendered, then this component accept the route props (match, location, history ).
When using componenttime, router will use React.createElementto create a new React elements of the given component. This means that if you use inline functions (inline function) to traditional values componentwill generate unnecessary duplication loaded. For inline rendering (inline rendering), recommended renderprop.

<Route path="/user/:username" component={User} />
const User = ({ match }) => {
  return <h1>Hello {match.params.username}!</h1>
}

render: func
This method is suitable for rendering the joint, and no loading problems said above is repeated.

// 内联渲染
<Route path="/home" render={() => <h1>Home</h1} />

// 包装 组合
const FadingRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    <FadeIn>
      <Component {...props} />
    </FaseIn>
  )} />
)

<FadingRoute path="/cool" component={Something} />

children: func
Sometimes you might just want to know whether the access address is matched, then change the next 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
anything that can be path-to-regexp valid URL path to resolution

<Route path="/users/:id" component={User} />

If you do not give a path, then the route will always match.

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

strict: bool
matching path trailing slashes. If it is true. path is '/ one /' will not match '/ one', but can match '/ one / two'.

If you want to make sure that the route does not end with a slash, strict and
exact all must be true

try it


<Link>

To provide declarative for your application, barrier-free navigation.

to: string
effect: Jump to specified path
usage scenarios: if simply jumps directly in the form of a string of path.

<Link to="/courses" />

  

to: object
effect: Jump to carry parameter specifies the path of
action scenes: for example, you click on this link to jump to the page needs to show the link corresponding to the content, but this is such a payment jump, you need to commodity prices and other information transfer past.

<Link to={{
  pathname: '/course',
  search: '?sort=name',
  state: { price: 18 }
}} />

replace: bool
to true, click on the link to use the new address will replace an address on the first visit, what does it mean, for example: you turn access '/ one' '/ two' '/ three' '/ four' four address, if rolled back, turn back to the retreat '/ three' '/ two' '/ one', in line with our expectations, while if we link '/ three' in replace to true. Click one two three four and then rolling back what will happen then? In turn retreat '/ three' '/ one' ! For this reason I made the online demo, you can debug taste!

In addition you can think of any use of this prop is it? Some people say that tab will be used to do with routing time. Welcome Message Discussion!

try it


<NavLink>

This is the <Link> special edition, as the name suggests this is in preparation for page navigation. Because navigation requires "active state."

activeClassName: string
navigation is activated when the application is selected the style name, the default style is namedactive

<NavLink
  to="/about"
  activeClassName="selected"
>MyBlog</NavLink>

activeStyle: object
If you do not want to use style names directly write style

<NavLink
  to="/about"
  activeStyle={{ color: 'green', fontWeight: 'bold' }}
>MyBlog</NavLink>

exact: bool
If true, the active style will be applied only when the access address exactly match

strict: bool
If true, the active style will be applied only when accessing the address suffix slash tight match (with or without)

isActive: func
decide whether to activate navigation, or do something else in the navigation activation time. In any case, it can not decide whether the corresponding page can be rendered.

try it


<Switch>

Only render the first match of the current access address <Route>or <Redirect>.

Consider the following code, if you visit /about, then the assembly About User Nomatch will be rendered, because the address of their corresponding routing and access /aboutmatch. This is obviously not what we want, we just want to render the first match of the route on it, then <Switch>came into being!

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>

You might ask, why not default RR4 mechanism in the first match to meet the requirements of it, Answer: This design allows us to more <Route> combination to the application, such as the sidebar (sidebars), bread crumbs, etc. Wait.

In addition, <Switch>for the transition animation is also very suitable, because the route is rendered and to be rendered before a routing node in the same position!

<Fade> 
  <Switch> 
    {/ * Switch used herein a route matches a time, only one node. * /} 
    <The Route /> 
    <the Route /> 
  </ Switch> 
</ Fade> 

<Fade> 
  <the Route /> 
  <the Route /> 
  {/ * Switch here might not match the plurality of routes, even if not match, also returns a null, the animation is calculated to increase some trouble. * /} 
</ Fade> 

children: node
<Switch> child nodes under only <Route>or <Redirect>elements. Only to be rendered to the current access address matches the first child only. <Route>Elements with their pathattributes match, <Redirect>the elements using their fromattributes match. If there is no corresponding pathor from, then they will match any current access address.

try it


<Redirect>

<Redirect> When you render will navigate to a new address, the new address in the address that covers the history of this inside information visit the visit.

to: String
the URL of the redirect string

to: Object
LOCATION target redirection

push: bool
If true, the operation will be redirected to the new address to access the history there, and can not fall back to the previous page.

from: string
to be matched will be redirected path.

try it


Prompt

When the user leaves the current page before making a few tips.

message: string
message when the user leaves the current page settings.

<Prompt message = "you sure you want to leave?" />

message: func
when the user leaves the current page, set back off function

<Prompt message={location => (
  `Are you sue you want to go to ${location.pathname}?` 
)} />

when: bool
by setting certain conditions to decide whether to enable Prompt

try it


Objectives and methods

history

histoty RR4 is one of two major dependence (another course React a), in different javascript environment, history to be able to travel to achieve a variety of session management (session) history.

We will often use the following terms:

  • "Browser history" - history implemented on DOM for support HTML5 history API browser
  • "Hash history" - history on the DOM implementation for older browsers.
  • "Memory history" - history on the implementation of memory, or for testing DOM environment (e.g. React Native).

history object generally has the following attributes and methods:

  • length: number View the number of entries in the history stack
  • action: string routing Jump to actions performed by the current page is divided into PUSH, REPLACE, POP
  • location: object object composition information of the current access address with the following properties:
  • pathname: string URL path
  • search: string URL query strings
  • hash: hash fragment string URL's
  • state: string such as performing push (path, state) operation, location of the state information to be provided in the stack, state and is valid only in browser memory history.
  • push (path, [state]) to add a new entry in the history stack inside information.
  • replace (path, [state]) replace the current entry in the history stack information in
  • Go (n) of the history stack pointer is moved forwardly n.
  • goBack () is equivalent to go (-1)
  • goForward equivalent to go (1)
  • block (prompt) to prevent Jump

history object is variable, because advice from <Route>the prop to get inside location, rather than directly from history.location. This ensures React lifecycle hook function normally performed, for example, the following code:

class Comp extends React.Component {
  componentWillReceiveProps(nextProps) {
    // locationChanged
    const locationChanged = nextProps.location !== this.props.location

    // 错误方式,locationChanged 永远为 false,因为history 是可变的
    const locationChanged = nextProps.history.location !== this.props.history.location
  }
}

location

location refers to your current location, you will go to the location, or the location before

{
  key: 'sdfad1'
  pathname: '/about',
  search: '?name=minooo'
  hash: '#sdfas',
  state: {
    price: 123
  }
}

The location object can be obtained in the following situations

  • In Route componentin order to get this.props.location
  • In Route renderthe order ({location}) => ( ) Gets manner
  • In Route childrenthe order ({location}) => ( ) Gets manner
  • In withRouter, gets to this.props.location way

location object does not change, so you can access to view the current page address is changed in the callback function using the location object life cycle. This technique is very useful in remote data acquisition and animation

componentWillReceiveProps (nextProps) { 
  IF (nextProps.location! == this.props.location) { 
    // have to jump up! 
  } 
}

Location can be used in different situations:

  • <Link to={location} />
  • <NaviveLink to={location} />
  • <Redirect to={location />
  • history.push(location)
  • history.replace(location)

match

match object contains <Route path> information on how to match the URL, with the following properties:

  • params: object path parameter value pairs obtained by parsing the URL of the dynamic part
  • isExact: When bool is true, the entire URL needs to match
  • path: string for pattern matching path for creating nested <Route>
  • url: string URL matching portion for nested <Link>

You can get match objects in the following situations

  • In Route componentin order to get this.props.match
  • In Route renderthe order ({match}) => ( ) Gets manner
  • In Route childrenthe order ({match}) => ( ) Gets manner
  • In the withRoutermiddle, the way to get to this.props.match
  • matchPath return value

When a Route is no path, it will match all paths.

Guess you like

Origin www.cnblogs.com/Ewarm/p/12022193.html