React Router API

一.<BrowserRouter>
<Router> 使用 HTML5 提供的 history API (pushState, replaceState 和 propstate 事件) 来保持 UI 和 URL 的同步。


import { BrowserRouter } from 'react-router-dom'
<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App/>
</BrowserRouter>


①basename: string
当前位置的基准 URL。如果你的页面部署在服务器的二级(子)目录,你需要将 basename 设置到此子目录。 正确的 URL 格式是前面有一个前导斜杠,但不能有尾部斜杠。


<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // 渲染为 <a href="/calendar/today">


②getUserConfirmation: func
当导航需要确认时执行的函数。默认使用 window.confirm。


// 使用默认的确认函数
const getConfirmation = (message, callback) => {
  const allowTransition = window.confirm(message)
  callback(allowTransition)
}
<BrowserRouter getUserConfirmation={getConfirmation}/>


③forceRefresh: bool
当设置为 true 时,在导航的过程中整个页面将会刷新。 只有当浏览器不支持 HTML5 的 history API 时,才设置为 true。


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


④keyLength: number
location.key 的长度。默认是 6。


<BrowserRouter keyLength={12}/>


⑤children: node
渲染单一子组件(元素)。




二、<HashRouter>
HashRouter 是一种特定的 <Router>, HashRouter 使用 URL 的 hash (例如:window.location.hash) 来保持 UI 和 URL 的同步。
注意: 使用 hash 的方式记录导航历史不支持 location.key 和 location.state。 在以前的版本中,我们为这种行为提供了 shim,但是仍有一些问题我们无法解决。 任何依赖此行为的代码或插件都将无法正常使用。 由于该技术仅用于支持传统的浏览器,因此在用于浏览器时可以使用 <BrowserHistory> 代替。


import { HashRouter } from 'react-router-dom'
<HashRouter>
  <App/>
</HashRouter>


①basename: string
当前位置的基准 URL。正确的 URL 格式是前面有一个前导斜杠,但不能有尾部斜杠。


<HashRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="#/calendar/today">


②getUserConfirmation: func
当导航需要确认时执行的函数。默认使用 window.confirm。


// 使用默认的确认函数
const getConfirmation = (message, callback) => {
  const allowTransition = window.confirm(message)
  callback(allowTransition)
}
<HashRouter getUserConfirmation={getConfirmation}/>


③hashType: string
window.location.hash 使用的 hash 类型。有如下几种:
    "slash" - 后面跟一个斜杠,例如 #/ 和 #/sunshine/lollipops
    "noslash" - 后面没有斜杠,例如 # 和 #sunshine/lollipops
    "hashbang" - Google 风格的 “ajax crawlable”,例如 #!/ 和 #!/sunshine/lollipops
默认为 "slash"。


④children: node
渲染单一子组件(元素)。




三、<Link>
为您的应用提供声明式的、无障碍导航。


import { Link } from 'react-router-dom'
<Link to="/about">关于</Link>


①to: string
需要跳转到的路径(pathname)或地址(location)。


<Link to="/courses"/>


②to: object
需要跳转到的地址(location)。


<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { fromDashboard: true }
}}/>


③replace: bool
当设置为 true 时,点击链接后将使用新地址替换掉访问历史记录里面的原地址。
当设置为 false 时,点击链接后将在原有访问历史记录的基础上添加一个新的纪录。
默认为 false。


<Link to="/courses" replace />


四、<NavLink>
A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL.
翻译:与当前URL匹配时将给渲染添加样式属性的特殊版本<Link>。


import { NavLink } from 'react-router-dom'
<NavLink to="/about">About</NavLink>


①activeClassName: string
The class to give the element when it is active. The default given class is active. This will be joined with the className prop.
翻译:当元素处于活动状态时给它的类。默认给定的类是活动的。这将与类名prop加入。


<NavLink
  to="/faq"
  activeClassName="selected"
>FAQs</NavLink>


②activeStyle: object
The styles to apply to the element when it is active.
翻译:当元素处于活动状态时应用的样式。 


<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: 'bold',
    color: 'red'
   }}
>FAQs</NavLink>


③exact: bool
When true, the active class/style will only be applied if the location is matched exactly.
翻译:确切地,当TRUE时,只有匹配位置时才应用活动类/样式。


<NavLink
  exact
  to="/profile"
>Profile</NavLink>


④strict: bool
When true, the trailing slash on a location’s pathname will be taken into consideration when determining if the location matches the current URL. See the <Route strict> documentation for more information.
翻译:当为真时,在斜线位置的路径将被纳入考虑,是否在确定位置匹配当前URL


<NavLink
  strict
  to="/events/"
>Events</NavLink>


⑤isActive: func
A function to add extra logic for determining whether the link is active. This should be used if you want to do more than verify that the link’s pathname matches the current URL’s pathname.
翻译:添加额外逻辑以确定链接是否活动的函数。这应使用如果你想做更多的验证链接的路径匹配当前URL的路径


// only consider an event active if its event id is an odd number
const 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>




五、<Prompt>
Re-exported from core Prompt




六、<MemoryRouter>
A <Router> that keeps the history of your “URL” in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.
翻译:保存内存中“URL”的历史(不读或写)的<路由器>到地址栏)。在测试和非浏览器环境中很有用,比如React Native。


import { MemoryRouter } from 'react-router'
<MemoryRouter>
  <App/>
</MemoryRouter>


①initialEntries: array
An array of locations in the history stack. These may be full-blown location objects with { pathname, search, hash, state } or simple string URLs.


<MemoryRouter
  initialEntries={[ '/one', '/two', { pathname: '/three' } ]}
  initialIndex={1}
>
  <App/>
</MemoryRouter>


②initialIndex: number
The initial location’s index in the array of initialEntries.


③getUserConfirmation: func
A function to use to confirm navigation. You must use this option when using <MemoryRouter> directly with a <Prompt>.


④keyLength: number
The length of location.key. Defaults to 6.


<MemoryRouter keyLength={12}/>


⑤children: node
A single child element to render.




七、<Redirect>
Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
翻译:渲染<重定向>将导航到一个新位置。新位置将历史记录堆栈中重写当前位置,如服务器端重定向(HTTP 3xx)。


import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>


①to: string
The URL to redirect to.


<Redirect to="/somewhere/else"/>


②to: object
A location to redirect to.


<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>


③push: bool
When true, redirecting will push a new entry onto the history instead of replacing the current one.
翻译:当TRUE时,重定向将推到历史上的新条目,而不是取代当前一个。


<Redirect push to="/somewhere/else"/>


④from: string
A pathname to redirect from. This can be used to match a location when rendering a <Redirect> inside of a <Switch>.
翻译:一个路径重定向到。这可以用来匹配渲染时的位置。<重定向> <开关>中的。


<Switch>
  <Redirect from='/old-path' to='/new-path'/>
  <Route path='/new-path' component={Place}/>
</Switch>


八、<Route>
The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when a location matches the route’s path.
翻译:路由组件可能是反应路由器中最重要的组件,用来理解和学习如何使用好。它最基本的职责是在某个位置与路由的路径匹配时呈现一些UI。


Consider the following code:
import { BrowserRouter as Router, Route } from 'react-router-dom'
<Router>
  <div>
    <Route exact path="/" component={Home}/>
    <Route path="/news" component={NewsFeed}/>
  </div>
</Router>


If the location of the app is / then the UI hierarchy will be something like:
<div>
  <Home/>
  <!-- react-empty: 2 -->
</div>


And if the location of the app is /news then the UI hierarchy will be:
<div>
  <!-- react-empty: 1 -->
  <NewsFeed/>
</div>


The “react-empty” comments are just implementation details of React’s null rendering. But for our purposes, it is instructive. A Route is always technically “rendered” even though its rendering null. As soon as the app location matches the route’s path, your component will be rendered.
翻译:“反应空”注释只是反应null渲染的实现细节。但就我们的目的而言,它是有教育意义的。路由始终在技术上“呈现”,即使其呈现空。当应用程序位置与路由的路径匹配时,组件将被呈现。


①Route render methods
There are 3 ways to render something with a <Route>:
    <Route component>
    <Route render>
    <Route children>
Each is useful in different circumstances. You should use only one of these props on a given <Route>. See their explanations below to understand why you have 3 options. Most of the time you’ll use component.
翻译:每个在不同的情况下都有用。在给定的<路线>中,只能使用这些道具中的一个。看看他们下面的解释,了解为什么你有3个选择。大多数情况下,您将使用组件。


②Route props
All three render methods will be passed the same three route props:
翻译:所有三种渲染方法都将通过相同的三个路径道具:
    match
    location
    history


③component
A React component to render only when the location matches. It will be rendered with route props.
翻译:仅当位置匹配时才会呈现的响应组件。它将用路线道具呈现。


When you use component (instead of render, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function you will get a lot of undesired remounting. For inline rendering, use the render prop (below).
翻译:当你使用组件(而不是渲染,下同)路由器使用react.createelement创建一个新的反应元件的组件。这意味着如果你提供一个内联函数,你会得到很多不需要的仪器。对于内联渲染,使用渲染道具(如下)。


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


④render: func
This allows for convenient inline rendering and wrapping without the undesired remounting explained above.
翻译:这允许方便的内联渲染和包装没有意外的重新解释以上。


Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop receives all the same route props as the component render prop.
翻译:与其使用组件支持为您创建一个新的响应元素,您可以传递一个在位置匹配时调用的函数。渲染道具接收所有相同的路线道具作为组件渲染道具。


// convenient inline rendering
<Route path="/home" render={() => <div>Home</div>}/>


// wrapping/composing
const FadingRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    <FadeIn>
      <Component {...props}/>
    </FadeIn>
  )}/>
)
<FadingRoute path="/cool" component={Something}/>


Warning: <Route component> takes precendence over <Route render> so don’t use both in the same <Route>.
翻译:警告:<路径> <路径优先在组件以使>所以不要用在同一个<路径>。


⑤children: func
Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.
翻译:有时需要渲染路径是否匹配位置。在这种情况下,您可以使用“函数”子道具。它完全像渲染一样工作,除非它被调用是否有匹配。


The children render prop receives all the same route props as the component and render methods, except when a route fails to match the URL, then match is null. This allows you to dynamically adjust your UI based on whether or not the route matches. Here we’re adding an active class if the route matches.
翻译:children渲染道具接收组件和渲染方法的所有相同的路线道具,但当路线与URL不匹配时,则匹配为空。这允许您根据路由是否匹配动态地调整用户界面。这里,如果路由匹配,我们将添加一个活动类。


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


const ListItemLink = ({ to, ...rest }) => (
  <Route path={to} children={({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}/>
)


This could also be useful for animations:
翻译:这也可能对动画有用:
<Route children={({ match, ...rest }) => (
  {/* Animate will always render, so you can use lifecycles
      to animate its child in and out */}
  <Animate>
    {match && <Something {...rest}/>}
  </Animate>
)}/>


Warning: Both <Route component> and <Route render> take precendence over <Route children> so don’t use more than one in the same <Route>.
翻译:警告:<路径>和<路径>组件提供优先在<<孩子>>路线,所以不要使用一个以上的在相同的<路径>。


⑥path: string
Any valid URL path that path-to-regexp understands.
翻译:这个路径来理解任何有效的URL路径表达式。 
Routes without a path always match.
翻译:路径的路由总是匹配的。


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


⑦exact: bool
When true, will only match if the path matches the location.pathname exactly.
翻译:如果为真,将只匹配如果路径匹配location.pathname到底。


<Route exact path="/one" component={About}/>


path location.pathname exact matches?
/one /one/two         true no
/one /one/two         false yes


⑧strict: bool
When true, a path that has a trailing slash will only match a location.pathname with a trailing slash. This has no effect when there are additional URL segments in the location.pathname.
翻译:当真实的路径具有一个斜线将只匹配一个斜线location.pathname。这没有影响时有额外的location.pathname URL片段。 


<Route strict path="/one/" component={About}/>


path location.pathname matches?
/one/ /one                 no
/one/ /one/                 yes
/one/ /one/two         yes


Warning: strict can be used to enforce that a location.pathname has no trailing slash, but in order to do this both strict and exact must be true.
翻译:警告:严格的可执行一个location.pathname没有斜线,但为了做到既严格和精确就这样。 


<Route exact strict path="/one" component={About}/>


path location.pathname matches?
/one /one                 yes
/one /one/                 no
/one /one/two         no




九、<Router>
The common low-level interface for all router components. Typically apps will use one of the high-level routers instead:
翻译:所有路由器组件的公共低级接口。通常,应用程序将使用一个高级路由器来代替: 
    <BrowserRouter>
    <HashRouter>
    <MemoryRouter>
    <NativeRouter>
    <StaticRouter>
The most common use-case for using the low-level <Router> is to synchronize a custom history with a state management lib like Redux or Mobx. Note that this is not required to use state management libs alongside React Router, it’s only for deep integration.
翻译:使用低级<路由器>最常见的是用状态管理来同步定制的histroy情况像Redux或Mobx。请注意,这并不需要使用状态管理LIBS和反应路由器,它只用于深层集成。 


custom history with a state management lib like Redux or Mobx. Note that this is not required to use state management libs alongside React Router, it’s only for deep integration.
翻译:同步定制的histroy情况像Redux或Mobx。请注意,这并不需要使用状态管理LIBS和反应路由器,它只用于深层集成。


import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()
<Router history={history}>
  <App/>
</Router>


①history: object
A history object to use for navigation.


import createBrowserHistory from 'history/createBrowserHistory'
const customHistory = createBrowserHistory()
<Router history={customHistory}/>


②children: node
A single child element to render.


<Router>
  <App/>
</Router>




十、<StaticRouter>
A <Router> that never changes location.
This can be useful in server-side rendering scenarios when the user isn’t actually clicking around, so the location never actually changes. Hence, the name: static. It’s also useful in simple tests when you just need to plug in a location and make assertions on the render output.
翻译:这在服务器端渲染场景中是有用的,因为用户实际上没有点击,所以位置实际上从未改变。因此,名称是静态的。当您需要插入一个位置并对呈现输出进行断言时,它在简单的测试中也很有用。
Here’s an example node server that sends a 302 status code for <Redirect>s and regular HTML for other requests:
翻译:下面是一个示例节点服务器,它为其他请求发送一个302状态代码,用于重定向和常规HTML: 
import { createServer } from 'http'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { StaticRouter } from 'react-router'
createServer((req, res) => {
  // This context object contains the results of the render
  const context = {}
  const html = ReactDOMServer.renderToString(
    <StaticRouter location={req.url} context={context}>
      <App/>
    </StaticRouter>
  )
  // context.url will contain the URL to redirect to if a <Redirect> was used
  if (context.url) {
    res.writeHead(302, {
      Location: context.url
    })
    res.end()
  } else {
    res.write(html)
    res.end()
  }
}).listen(3000)


①basename: string
The base URL for all locations. A properly formatted basename should have a leading slash, but no trailing slash.
翻译:所有位置的基本URL。格式正确的是:应该有一个斜杠,但没有斜线。


<StaticRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</StaticRouter>


②location: string
The URL the server received, probably req.url on a node server.
翻译:URL服务器接收,可能req.url节点上的服务器。 


<StaticRouter location={req.url}>
  <App/>
</StaticRouter>


③location: object
A location object shaped like { pathname, search, hash, state }


<StaticRouter location={{ pathname: '/bubblegum' }}>
  <App/>
</StaticRouter>


④children: node
A single child element to render




十一、<Switch>
Renders the first child <Route> or <Redirect> that matches the location.
翻译:呈现匹配位置的第一个子项<路由>或<重定向>。 
How is this different than just using a bunch of <Route>s?
翻译:这与使用一系列<路由> s有什么不同? 
<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively. Consider this code:
翻译:<开关>是唯一的,它只显示一条路由。相反,每一个<路径>相匹配的位置呈现“。考虑这个代码:
<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>


If the URL is /about, then <About>, <User>, and <NoMatch> will all render because they all match the path. This is by design, allowing us to compose <Route>s into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc.
翻译:如果URL /,然后<关于>,<用户名>和<NoMatch>,编写都会使他们都匹配的路径。这是通过设计,让我们谱写<路径>为我们在许多方面的应用,如侧边栏和面包屑,引导标签,等等。


Occasionally, however, we want to pick only one <Route> to render. If we’re at /about we don’t want to also match /:user (or show our “404” page). Here’s how to do it with Switch:
翻译:然而,偶尔我们只想选择一个<渲染>路径。如果我们在/我们也不想匹配/:用户(或显示我们的“404”页)。下面是如何用开关来实现它:


import { Switch, Route } from 'react-router'
<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>


Now, if we’re at /about, <Switch> will start looking for a matching <Route>. <Route path="/about"/> will match and <Switch> will stop looking for matches and render <About>. Similarly, if we’re at /michael then <User> will render.


This is also useful for animated transitions since the matched <Route> is rendered in the same position as the previous one.
翻译:这对于动画转换也是有用的,因为匹配的<路径>与前面的位置相同。


<Fade>
  <Switch>
    {/* there will only ever be one child here */}
    <Route/>
    <Route/>
  </Switch>
</Fade>


<Fade>
  <Route/>
  <Route/>
  {/* there will always be two children here,
      one might render null though, making transitions
      a bit more cumbersome to work out */}
</Fade>


①children: node
All children of a <Switch> should be <Route> or <Redirect> elements. Only the first child to match the current location will be rendered.


<Route> elements are matched using their path prop and <Redirect> elements are matched using their from prop. A <Route> with no path prop or a <Redirect> with no from prop will always match the current location.


<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/users" component={Users}/>
  <Redirect from="/accounts" to="/users"/>
  <Route component={NoMatch}/>
</Switch>


十二、history
The term “history” and "history object" in this documentation refers to the history package, which is one of only 2 major dependencies of React Router (besides React itself), and which provides several different implementations for managing session history in JavaScript in various environments.


The following terms are also used:
    “browser history” - A DOM-specific implementation, useful in web browsers that support the HTML5 history API
    “hash history” - A DOM-specific implementation for legacy web browsers
    “memory history” - An in-memory history implementation, useful in testing and non-DOM environments like React Native


history objects typically have the following properties and methods:
    length - (number) The number of entries in the history stack
    action - (string) The current action (PUSH, REPLACE, or POP)
    location - (object) The current location. May have the following properties:
        pathname - (string) The path of the URL
        search - (string) The URL query string
        hash - (string) The URL hash fragment
        state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
    push(path, [state]) - (function) Pushes a new entry onto the history stack
    replace(path, [state]) - (function) Replaces the current entry on the history stack
    go(n) - (function) Moves the pointer in the history stack by n entries
    goBack() - (function) Equivalent to go(-1)
    goForward() - (function) Equivalent to go(1)
    block(prompt) - (function) Prevents navigation (see the history docs)


①history is mutable
The history object is mutable. Therefore it is recommended to access the location from the render props of <Route>, not from history.location. This ensures your assumptions about React are correct in lifecycle hooks. For example:


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


    // INCORRECT, will *always* be false because history is mutable.
    const locationChanged = nextProps.history.location !== this.props.history.location
  }
}
<Route component={Comp}/>


Additional properties may also be present depending on the implementation you’re using. Please refer to the history documentation for more details.


十三、location
Locations represent where the app is now, where you want it to go, or even where it was. It looks like this:


{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere'
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}


The router will provide you with a location object in a few places:
    Route component as this.props.location
    Route render as ({ location }) => ()
    Route children as ({ location }) => ()
    withRouter as this.props.location
t is also found on history.location but you shouldn’t use that because its mutable. You can read more about that in the history doc.


A location object is never mutated so you can use it in the lifecycle hooks to determine when navigation happens, this is really useful for data fetching and animation.
animation.


componentWillReceiveProps(nextProps) {
  if (nextProps.location !== this.props.location) {
    // navigated!
  }
}


You can provide locations instead of strings to the various places that navigate:
    Web Link to
    Native Link to
    Redirect to
    history.push
    history.replace
Normally you just use a string, but if you need to add some “location state” that will be available whenever the app returns to that specific location, you can use a location object instead. This is useful if you want to branch UI based on navigation history instead of just paths (like modals).


// usually all you need
<Link to="/somewhere"/>
// but you can use a location instead
const location = {
  pathname: '/somewhere'
  state: { fromDashboard: true }
}
<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)


Finally, you can pass a location to the following components:
    Route
    Switch
This will prevent them from using the actual location in the router’s state. This is useful for animation and pending navigation, or any time you want to trick a component into rendering at a different location than the real one.


十四、match
A match object contains information about how a <Route path> matched the URL. match objects contain the following properties:
翻译:匹配对象包含关于路由路径>匹配URL的信息。匹配对象包含以下属性:
    params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path(键/值对从与路径动态段相对应的URL解析。)
    isExact - true if the entire URL was matched (no trailing characters)(如果整个URL匹配(没有尾随字符),则为true。)
    path - (string) The path pattern used to match. Useful for building nested <Route>s(用于匹配的路径模式。用于构建嵌套的<路由>)
    url - (string) The matched portion of the URL. Useful for building nested <Link>s(URL的匹配部分。用于构建嵌套的<链接>)


You’ll have access match objects in various places:
翻译:您将在不同的地方访问匹配对象: 
    Route component as this.props.match
    Route render as ({ match }) => ()
    Route children as ({ match }) => ()
    withRouter as this.props.match
    matchPath as the return value


If a Route does not have a path, and therefore always matches, you’ll get the closest parent match. Same goes for withRouter.
如果一条路由没有路径,因此总是匹配,那么将得到最接近的父匹配。withRouter同样也是.


十五、matchPath
This lets you use the same matching code that <Route> uses except outside of the normal render cycle, like gathering up data dependencies before rendering on the server.


import { matchPath } from 'react-router'
const match = matchPath('/users/123', {
  path: '/users/:id'
  exact: true,
  strict: false
})


①pathname
The first argument is the pathname you want to match. If you’re using this on the server with Node.js, it would be req.url.


②props
The second argument are the props to match against, they are identical to the matching props Route accepts:


{
  path, // like /users/:id
  strict, // optional, defaults to false
  exact // optional, defaults to false
}


十六、withRouter
You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.


import React, { PropTypes } from 'react'
import { withRouter } from 'react-router'
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }
  render() {
    const { match, location, history } = this.props


    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)


Important Note
If you are using withRouter to prevent updates from being blocked by shouldComponentUpdate, it is important that withRouter wraps the component that implements shouldComponentUpate. For example, when using Redux:


// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent)
// This does not
connect(...)(withRouter(MyComponent))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值