React Router API文档

一、<BrowserRouter>

使用HTML5历史记录API(pushState,replaceState和popstate事件)的<Router>来保持您的UI与URL同步。

  1. import { BrowserRouter } from 'react-router-dom'
  2.  
  3. <BrowserRouter
  4. basename={optionalString}
  5. forceRefresh={optionalBool}
  6. getUserConfirmation={optionalFunc}
  7. keyLength={optionalNumber}
  8. >
  9. <App/>
  10. </BrowserRouter>

属性:

1、 basename: string

所有locations的基本URL。如果应用程序从服务器上的子目录提供,则需要将其设置为子目录。正确格式的基础名称应该有一个主要的斜杠,但没有尾部斜线。

  1. <BrowserRouter basename="/calendar"/>
  2. <Link to="/today"/> // renders <a href="/calendar/today">

2、getUserConfirmation: func

用于确认导航的功能。默认使用window.confirm。

  1. // this is the default behavior
  2. const getConfirmation = (message, callback) => {
  3. const allowTransition = window.confirm(message)
  4. callback(allowTransition)
  5. }
  6.  
  7. <BrowserRouter getUserConfirmation={getConfirmation}/>

3、forceRefresh: bool

如果为true,则路由器将在页面导航中使用全页刷新。您可能只想在不支持HTML5历史记录API的浏览器中使用此功能。

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

4、keyLength: number

location.key的长度。默认为6。

  1. <BrowserRouter keyLength={12}/>

5、children: node

要呈现的单个子元素。

二、<HashRouter>

使用URL的哈希部分(即window.location.hash)的<Router>来保持您的UI与URL同步。

提示:Hash history不支持location.key或location.state。
任何需要此行为的代码或插件将无法正常工作。由于此技术仅用于支持旧版浏览器,因此我们建议您将服务器配置为使用<BrowserHistory>。

  1. import { HashRouter } from 'react-router-dom'
  2.  
  3. <HashRouter>
  4. <App/>
  5. </HashRouter>

1、basename: string

所有locations的基本URL。正确格式的基础名称应该有一个主要的斜杠,但没有尾部斜线。

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

2、getUserConfirmation: func

用于确认导航的功能。默认使用window.confirm。

  1. // this is the default behavior
  2. const getConfirmation = (message, callback) => {
  3. const allowTransition = window.confirm(message)
  4. callback(allowTransition)
  5. }
  6. <HashRouter getUserConfirmation={getConfirmation}/>

3、hashType: string

用于window.location.hash的编码类型。可用值为:

"slash": 创建一个hash值,例如:#/ and #/sunshine/lollipops
"noslash": 创建一个hash值,例如:# and #sunshine/lollipops
”hashbang“: 创建一个”ajax crawlable” (已被谷歌弃用) 例如:#!/ and #!/sunshine/lollipops

默认值"slash"

4、children: node
要呈现的单个子元素。

三、<Link>

在应用程序范围提供声明性,可访问的导航

  1. import { Link } from 'react-router-dom'
  2.  
  3. <Link to="/about">About</Link>

1、to: string

链接到的路径名或位置。

  1. <Link to="/courses"/>

2、to: object

要链接的位置。

  1. <Link to={{
  2. pathname: '/courses',
  3. search: '?sort=name',
  4. hash: '#the-hash',
  5. state: { fromDashboard: true }
  6. }}/>

3、replace: bool

如果为true,单击链接将替换历史堆栈中的当前条目,而不是添加新条目。

  1. <Link to="/courses" replace />

四、<NavLink>

一种特殊版本的<Link>,当与当前URL匹配时,将向渲染元素添加样式属性。

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

1、activeClassName: string

当活动时给出元素的类。默认给定类是活动的。这将与className支持相结合。

  1. <NavLink
  2. to="/faq"
  3. activeClassName="selected"
  4. >FAQs</NavLink>

2、activeStyle: object

当元素处于活动状态时应用于元素的样式。

  1. <NavLink
  2. to="/faq"
  3. activeStyle={{
  4. fontWeight: 'bold',
  5. color: 'red'
  6. }}
  7. >FAQs</NavLink>

3、exact: bool

当为true时,仅当位置匹配完全时才会应用活动类/样式。

  1. <NavLink
  2. exact
  3. to="/profile"
  4. >Profile</NavLink>

4、strict: bool

当为真时,在确定位置是否与当前网址匹配时,将考虑位置路径名上的尾部斜线。
有关详细信息,请参阅<Route strict>文档。(https://reacttraining.com/core/api/Route/strict-bool)

  1. <NavLink
  2. strict
  3. to="/events/"
  4. >Events</NavLink>

5、isActive: func

增加用于确定链接是否活动的额外逻辑的功能。如果您想要更多地验证链接的路径名与当前URL的路径名匹配,则应该使用这一点。

  1. // 只有当事件ID为奇数时,才考虑事件有效
  2. const oddEvent = (match, location) => {
  3. if (!match) {
  4. return false
  5. }
  6. const eventID = parseInt(match.params.eventID)
  7. return !isNaN(eventID) && eventID % 2 === 1
  8. }
  9.  
  10. <NavLink
  11. to="/events/123"
  12. isActive={oddEvent}
  13. >Event 123</NavLink>

6、location: object

isActive比较当前的历史位置(通常是当前的浏览器URL)。要与其他位置进行比较,可以传递一个位置。

五、<Prompt>

https://reacttraining.com/core/api/Prompt

六、<MemoryRouter>

将“URL”的历史记录保存在内存中(不读取或写入地址栏)的<路由器>。在测试和非浏览器环境(如React Native)中很有用

  1. import { MemoryRouter } from 'react-router'
  2.  
  3. <MemoryRouter>
  4. <App/>
  5. </MemoryRouter>

1、initialEntries: array

历史堆栈中的一系列位置。这些可能是具有{pathname,search,hash,state}或简单字符串URL的完整的位置对象。

  1. <MemoryRouter
  2. initialEntries={[ '/one', '/two', { pathname: '/three' } ]}
  3. initialIndex={1}
  4. >
  5. <App/>
  6. </MemoryRouter>

2、initialIndex: number

initialEntries数组中的初始位置索引。

3、getUserConfirmation: func

用于确认导航的功能。当使用<MemoryRouter>直接使用<Prompt>时,必须使用此选项。

4、keyLength: number

location.key的长度。默认为6

  1. <MemoryRouter keyLength={12}/>

5、children: node

要呈现的单个子元素。

七、<Redirect>

渲染<Redirect>将导航到新位置。新位置将覆盖历史堆栈中的当前位置,如服务器端重定向(HTTP 3xx)。

  1. import { Route, Redirect } from 'react-router'
  2.  
  3. <Route exact path="/" render={() => (
  4. loggedIn ? (
  5. <Redirect to="/dashboard"/>
  6. ) : (
  7. <PublicHomePage/>
  8. )
  9. )}/>

1、to: string

要重定向到的网址。

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

2、to: object

要重定向到的位置。

  1. <Redirect to={{
  2. pathname: '/login',
  3. search: '?utm=your+face',
  4. state: { referrer: currentLocation }
  5. }}/>

3、push: bool

当为true时,重定向会将新条目推入历史记录,而不是替换当前条目。

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

4、from: string

要重定向的路径名。这只能用于在<Switch>内部呈现<Redirect>时匹配位置。
有关详细信息,请参阅<Switch children>。https://reacttraining.com/web/api/Switch/children-node

  1. <Switch>
  2. <Redirect from='/old-path' to='/new-path'/>
  3. <Route path='/new-path' component={Place}/>
  4. </Switch>

八、<Route>

路由组件可能是React Router中了解和学习使用的最重要的组件。其最基本的责任是在位置与路线的路径匹配时呈现一些UI。

  1. import { BrowserRouter as Router, Route } from 'react-router-dom'
  2.  
  3. <Router>
  4. <div>
  5. <Route exact path="/" component={Home}/>
  6. <Route path="/news" component={NewsFeed}/>
  7. </div>
  8. </Router>
  9. <Home/>
  10. <!-- react-empty: 2 -->
  11. </div>
  12. <!-- react-empty: 1 -->
  13. <NewsFeed/>
  14. </div>

九、Route render methods

有3种方法可以使用<Route>呈现某些东西:

<Route component>
 <Route render>
 <Route children>

每个在不同的情况下都有用。您只能在给定的<Route>上使用这些方法之一。请看下面的解释,了解为什么你有3个选项。大多数时候你会使用component。

Route props

所有三个渲染方法将通过相同的三个route props

match
location
history

1、component

仅当位置匹配时才呈现的React组件.它将与route props一起呈现。

当您使用组件(而不是下面的渲染或子项)时,路由器使用React.createElement从给定组件创建一个新的React元素。
这意味着如果您向组件属性提供内联函数,则可以在每个渲染中创建一个新组件.这将导致现有组件卸载和新组件安装,而不是仅更新现有组件
当使用内联函数进行内联渲染时,请使用render或child(下文)

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

2、render: func

这允许方便的在线呈现和包装,而不需要上述的不期望的重新安装。您可以使用组件支持为您创建一个新的React元素,而不必在位置匹配时传入要调用的函数。
渲染道具接收与组件渲染道具相同的所有route props。

警告:<Route component>取决于<Route render>,所以不要在同一个<Route>中使用两者

  1. // 内联呈现
  2. <Route path="/home" render={() => <div>Home</div>}/>
  3.  
  4. // 包装/合成
  5. const FadingRoute = ({ component: Component, ...rest }) => (
  6. <Route {...rest} render={props => (
  7. <FadeIn>
  8. <Component {...props}/>
  9. </FadeIn>
  10. )}/>
  11. )
  12.  
  13. <FadingRoute path="/cool" component={Something}/>

3、children: func

有时您需要渲染路径是否匹配该位置。在这些情况下,可以使用函数child prop。它的工作原理就像渲染,除了它被调用是否有匹配
children 渲染prop接收与组件和渲染方法相同的所有route props,除非路由未能匹配URL,则match为null。
这允许您根据路线是否匹配来动态调整用户界面。在这里,如果路由匹配,我们添加一个活动类

警告:<Route component>和<Route render>优先级高于<Route children>,所以不要在同一个<Route>中使用多个

  1. <ul>
  2. <ListItemLink to="/somewhere"/>
  3. <ListItemLink to="/somewhere-else"/>
  4. </ul>
  5.  
  6. const ListItemLink = ({ to, ...rest }) => (
  7. <Route path={to} children={({ match }) => (
  8. <li className={match ? 'active' : ''}>
  9. <Link to={to} {...rest}/>
  10. </li>
  11. )}/>
  12. )
  13.  
  14. //可以用于动画
  15. <Route children={({ match, ...rest }) => (
  16. {/* Animate will always render, so you can use lifecycles
  17. to animate its child in and out */}
  18. <Animate>
  19. {match && <Something {...rest}/>}
  20. </Animate>
  21. )}/>

4、path: string

path-to-regexp理解的任何有效的URL路径。

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

5、exact: bool

当为true时,仅当路径与location.pathname完全匹配时才匹配。

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

______________________________________________
| path | location.pathname | exact | matches? |

| /one | /one/two             | true   | no            |

| /one | /one/two             | false  | yes           |
----------------------------------------------

6、strict: bool

当为true时,具有尾部斜杠的路径将仅与具有尾部斜杠的location.pathname匹配。当在location.pathname中有其他URL段时,这不起作用。

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

________________________________________
| path | location.pathname | matches? |

| /one/ | /one                  | no           |

| /one/ | /one/                | yes          |

| /one/ | /one/two           | yes          |
----------------------------------------

警告:strict可以用来强制执行location.pathname没有尾部斜杠,但为了做到这一点,strict和exact必须是true。

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

________________________________________
| path | location.pathname | matches? |

| /one | /one                   | yes |

| /one | /one/                 | no |

| /one | /one/two            | no |
----------------------------------------

7、location: object

<Route>元素尝试将其路径与当前历史记录位置(通常是当前浏览器URL)进行匹配。但是,也可以传递具有不同路径名的位置进行匹配。
https://reacttraining.com/react-router/location.md

当您需要将<Route>匹配到当前历史记录位置以外的位置时,这是非常有用的,如“动画转换”示例所示。
https://reacttraining.com/react-router/web/example/animated-transitions

如果<Switch>元素包裹在<Switch>中并匹配传递给<Switch>(或当前历史位置)的位置,则传递给<Route>的位置prop将被<开关>(在此给出)
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Switch.js#L51

十、<Router>

所有路由器组件的通用低级接口。通常,应用程序将使用其中一个高级路由器:

<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>

使用低级“路由器”最常见的用例是将自定义历史记录与状态管理库(如Redux或Mobx)进行同步。请注意,这不是与React Router一起使用状态管理库,而只用于深度集成。

  1. import { Router } from 'react-router'
  2. import createBrowserHistory from 'history/createBrowserHistory'
  3.  
  4. const history = createBrowserHistory()
  5.  
  6. <Router history={history}>
  7. <App/>
  8. </Router>

1、history: object

用于导航的历史对象。

  1. import createBrowserHistory from 'history/createBrowserHistory'
  2.  
  3. const customHistory = createBrowserHistory()
  4. <Router history={customHistory}/>

2、children: node

要呈现的单个子元素。

  1. <Router>
  2. <App/>
  3. </Router>

十一、<StaticRouter>

一个从不改变位置的<Router>。

当用户实际上没有点击时,这在服务器端渲染场景中很有用,因此该位置从未实际改变。因此,名称:static。当您只需插入一个位置并在渲染输出上作出断言时,它也可用于简单的测试。

以下是一个示例节点服务器,为<Redirect>发送302状态代码,并为其他请求发送常规HTML

  1. import { createServer } from 'http'
  2. import React from 'react'
  3. import ReactDOMServer from 'react-dom/server'
  4. import { StaticRouter } from 'react-router'
  5.  
  6. createServer((req, res) => {
  7.  
  8. // This context object contains the results of the render
  9. const context = {}
  10.  
  11. const html = ReactDOMServer.renderToString(
  12. <StaticRouter location={req.url} context={context}>
  13. <App/>
  14. </StaticRouter>
  15. )
  16.  
  17. // context.url will contain the URL to redirect to if a <Redirect> was used
  18. if (context.url) {
  19. res.writeHead(302, {
  20. Location: context.url
  21. })
  22. res.end()
  23. } else {
  24. res.write(html)
  25. res.end()
  26. }
  27. }).listen(3000)

1、basename: string

所有位置的基本URL。正确格式化的基础名称应该有一个主要的斜杠,但没有尾部斜线

  1. <StaticRouter basename="/calendar">
  2. <Link to="/today"/> // renders <a href="/calendar/today">
  3. </StaticRouter>

2、location: string

服务器接收到的URL,可能是节点服务器上的req.url。

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

3、location: object

一个像{pathname,search,hash,state}的位置对象

  1. <StaticRouter location={{ pathname: '/bubblegum' }}>
  2. <App/>
  3. </StaticRouter>

4、context: object

一个简单的JavaScript对象。在渲染过程中,组件可以向对象添加属性以存储有关渲染的信息。

  1. const context = {}
  2. <StaticRouter context={context}>
  3. <App />
  4. </StaticRouter>

当<Route>匹配时,它会将context对象传递给它作为staticContext prop所呈现的组件。查看“服务器渲染”指南,
https://reacttraining.com/web/guides/server-rendering 了解有关如何自行执行此操作的更多信息。

渲染后,这些属性可用于配置服务器的响应。

5、children: node

十二、<Switch>

渲染与位置匹配的第一个子元素<Route> 或 <Redirect> 。

<Switch>是独特的,因为它仅仅渲染一个路由。相反,与位置匹配的每个<Route>都会包含。

参考以下代码:

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

如果URL是/about,则<About>,<User>和<NoMatch>将全部渲染,因为它们都与路径匹配。这是通过设计,允许我们以许多方式将<Route>组合到我们的应用程序中,如侧边栏和面包屑,引导标签等。

然而,偶尔,我们只想选择一个<路线>来渲染。如果我们在/关于我们不想也匹配/:用户(或显示我们的“404”页面)。以下是使用Switch的方法:

  1. import { Switch, Route } from 'react-router'
  2.  
  3. <Switch>
  4. <Route exact path="/" component={Home}/>
  5. <Route path="/about" component={About}/>
  6. <Route path="/:user" component={User}/>
  7. <Route component={NoMatch}/>
  8. </Switch>

现在,如果我们在/ about,<Switch>将开始寻找匹配的<Route>。 <Route path =“/ about”/>将匹配,<Switch>将停止寻找匹配并呈现<About>。同样,如果我们在/ michael,那么<User>将呈现。

这对于动画转换也是有用的,因为匹配的<Route>呈现与前一个相同的位置。

  1. <Fade>
  2. <Switch>
  3. {/* there will only ever be one child here */}
  4. <Route/>
  5. <Route/>
  6. </Switch>
  7. </Fade>
  8.  
  9. <Fade>
  10. <Route/>
  11. <Route/>
  12. {/* there will always be two children here,
  13. one might render null though, making transitions
  14. a bit more cumbersome to work out */}
  15. </Fade>

十三、Switch props

1、location: object

要用于匹配子元素而不是当前历史位置(通常是当前浏览器URL)的位置对象。

2、children: node

<Switch>的所有子项应为<Route>或<Redirect>元素。只有匹配当前位置的第一个子元素才会呈现

<Route>元素使用它们的路径匹配匹配,并且<Redirect>元素使用它们与prop相匹配。没有路径的<Route>或路由不正确的<Redirect>将始终与当前位置匹配。

当您在<Switch>中包含<Redirect>时,它可以使用任何<Route>的位置匹配道具:path,exact和strict。只是path prop的别名。

如果给定位置支持<Switch>,它将覆盖匹配的子元素上的path prop。

  1. <Switch>
  2. <Route exact path="/" component={Home}/>
  3.  
  4. <Route path="/users" component={Users}/>
  5. <Redirect from="/accounts" to="/users"/>
  6.  
  7. <Route component={NoMatch}/>
  8. </Switch>

十四、history

本文档中的“历史”和“历史对象”一词是指历史包,https://github.com/ReactTraining/history 这是React 
Router的唯一两个主要依赖之一(除了React本身)之外,并且其提供用于在各种环境中的JavaScript中管理会话历史的几种不同实现

使用以下术语:

“browser history” : DOM特定的实现,可用于支持HTML5历史记录API的Web浏览器
“hash history” : 遗留网络浏览器的DOM特定实现
“memory history” : 内存中的历史记录实现,可用于测试和非DOM环境(如React Native)

history对象通常具有以下属性和方法:

length : (number)历史堆栈中的条目数
action : (string)当前动作(PUSH,REPLACE或POP)
location : (object) 当前位置。具有以下属性:
pathname: URL的路径
search: URL查询字符串
hash: URL哈希片段
state: 位置特定的状态被提供给例如。当这个位置被推到堆栈上时,push(路径,状态)。仅在浏览器和内存历史记录中可用。
push : (path, [state]) - (function) 将新条目推入历史堆栈
replace : (path, [state]) - (function) 替换历史堆栈上的当前条目
go(n) : (function) 将历史堆栈中的指针移动n个条目
goBack() : (function) 相当于 go(-1)
goForward() : (function) 相当于 go(1)
block : (function) 防止导航 (https://github.com/ReactTraining/history#blocking-transitions)

十五、history is mutable

history 对象是可变的。因此,建议从<Route>的渲染道具访问位置,而不是从history.location访问。这样可以确保您对于React的假设在生命周期挂钩中是正确的。例如:

  1. class Comp extends React.Component {
  2. componentWillReceiveProps(nextProps) {
  3. // will be true
  4. const locationChanged = nextProps.location !== this.props.location
  5.  
  6. // INCORRECT, will *always* be false because history is mutable.
  7. const locationChanged = nextProps.history.location !== this.props.history.location
  8. }
  9. }
  10.  
  11. <Route component={Comp}/>

详细信息参考:https://github.com/ReactTraining/history#properties

十六、location

位置代表了应用程序现在的位置,您想要哪里,甚至是哪里。看起来像这样

  1. {
  2.   key: 'ac3df4', // not with HashHistory!
  3.   pathname: '/somewhere'
  4.   search: '?some=search-string',
  5.   hash: '#howdy',
  6.   state: {
  7.     [userDefined]: true
  8.   }
  9. }

路由器将在几个地方为您提供位置对象

Route component as this.props.location
Route render as ({ location }) => ()
Route children as ({ location }) => ()
withRouter as this.props.location

它也发现在history.location,但你不应该使用它,因为它的可变。您可以在历史文档中阅读更多信息。

https://reacttraining.com/web/api/history

位置对象从不被突变,因此您可以在生命周期钩子中使用它来确定何时导航,这对数据获取和动画非常有用。

  1. componentWillReceiveProps(nextProps) {
  2.   if (nextProps.location !== this.props.location) {
  3.    // navigated!
  4.   }
  5. }

您可以提供位置而不是字符串到导航的各个地方:

Web Link to
Native Link to
Redirect to
history.push
history.replace

通常您只需使用一个字符串,但如果您需要添加一些“位置状态”,只要应用程序返回到该特定位置,就可以使用位置对象。如果您想基于导航历史而不仅仅是路径(如模态)分支UI,这很有用。

// 最常用的

  1. <Link to="/somewhere"/>
  2.  
  3. // but you can use a location instead
  4. const location = {
  5. pathname: '/somewhere'
  6. state: { fromDashboard: true }
  7. }
  8.  
  9. <Link to={location}/>
  10. <Redirect to={location}/>
  11. history.push(location)
  12. history.replace(location)

最后,您可以将location传递给以下组件:

Route   (https://reacttraining.com/web/api/Route/location)
Switch  (https://reacttraining.com/web/api/Route/location)

十七、match

匹配对象包含有关<Route path>如何匹配URL的信息。匹配对象包含以下属性:

params - (object)从对应于路径的动态段的URL解析的键/值对
isExact - (boolean)true如果整个URL匹配(没有尾随字符
path - (string)用于匹配的路径模式。作用于构建嵌套的<Route>
url - (string)URL的匹配部分。作用于构建嵌套的<Link> s

可以在以下地方访问匹配对象:

Route component as this.props.match
Route render as ({ match }) => ()
Route children as ({ match }) => ()
withRouter as this.props.match
matchPath as the return value

如果路由没有路径,因此始终匹配,您将获得最接近的父级匹配。与Router一样。

十八、matchPath

这允许您使用除了正常渲染循环之外的<Route>使用相同的匹配代码,例如在服务器上渲染之前收集数据依赖关系。

  1. import { matchPath } from 'react-router'
  2.  
  3. const match = matchPath('/users/123', {
  4.   path: '/users/:id',
  5.   exact: true,
  6.   strict: false
  7. })

1、pathname

第一个参数是要匹配的路径名。如果在Node.js的服务器上使用这个,那么它将是req.url。

2、props

第二个参数是匹配的道具,它们与匹配props相同route接受:

  1. {
  2.   path, // like /users/:id
  3.   strict, // optional, defaults to false
  4.   exact // optional, defaults to false
  5. }

3、withRouter

您可以通过withRouter高阶组件访问历史对象的属性和最接近的<Route>的匹配。随着路由每次路由改变时,路由器会重新渲染其组件,路径与<路径>渲染道具:{match,location,history}相同。

  1. import React from 'react'
  2. import PropTypes from 'prop-types'
  3. import { withRouter } from 'react-router'
  4.  
  5. // A simple component that shows the pathname of the current location
  6. class ShowTheLocation extends React.Component {
  7.   static propTypes = {
  8.     match: PropTypes.object.isRequired,
  9.     location: PropTypes.object.isRequired,
  10.     history: PropTypes.object.isRequired
  11.   }
  12.  
  13.   render() {
  14.     const { match, location, history } = this.props
  15.  
  16.     return (
  17.       <div>You are now at {location.pathname}</div>
  18.     )
  19.   }
  20. }
  21.  
  22. // Create a new component that is "connected" (to borrow redux
  23. // terminology) to the router.
  24. const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

提示

如果您使用withRouter来阻止更新被shouldComponentUpdate阻止,那么重要的是使用Router打包实现shouldComponentUpdate的组件。例如,使用Redux时

  1. // This gets around shouldComponentUpdate
  2. withRouter(connect(...)(MyComponent))
  3. // This does not
  4. connect(...)(withRouter(MyComponent))

有关详细信息,请参阅本指南。 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md

静态方法和属性

包装组件的所有非反应特定静态方法和属性将自动复制到“已连接”组件。

十九、Component.WrappedComponent

被包装的组件在返回的组件上作为静态属性WrappedComponent公开,可以用于单独测试组件。

  1. // MyComponent.js
  2. export default withRouter(MyComponent)
  3.  
  4. // MyComponent.test.js
  5.  
  6. import MyComponent from './MyComponent'
  7. render(<MyComponent.WrappedComponent location={{...}} ... />)

二十、wrappedComponentRef: func

将作为参考传递给包装组件的函数。

  1. class Container extends React.Component {
  2.   componentDidMount() {
  3.     this.component.doSomething()
  4.   }
  5.  
  6.   render() {
  7.     return (
  8.       <MyComponent wrappedComponentRef={c => this.component = c}/>
  9.     )
  10.   }
  11. }

React Router API文档的更多相关文章

  1. Angularjs在线api文档

    http://docs.ngnice.com/api            文档 http://www.ngnice.com/showcase/#/home/home                  ...

  2. 12 Django Rest Swagger生成api文档

    01-简介 Swagger:是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的Web服务.总体目标是使客户端和文件系统源代码作为服务器以同样的速度来更新.当接口有变动时,对应的接 ...

  3. Api 文档管理系统 RAP2 环境搭建

    Api 文档管理系统 RAP2 环境搭建  发表于 2018-03-27 |  分类于 Api |  评论数: 4|  阅读次数: 4704  本文字数: 4.8k |  阅读时长 ≍ 9 分钟 RA ...

  4. go实践之swagger自动生成api文档

    文章目录 go实践之swagger自动生成api文档 1.安装需要用到的包 2.接口代码支持swagger 3. 生成swagger接口 go实践之swagger自动生成api文档 作为一个后端开发, ...

  5. xadmin引入drf-yasg生成Swagger API文档

    一.安装drf-yasg: 由于django-rest-swagger已经废弃了 所以引入了drf-yasg pip install drf-yasg 安装install drf-yasg库 http ...

  6. Go学习笔记(六) | 使用swaggo自动生成Restful API文档(转)

    关于Swaggo 或许你使用过Swagger, 而 swaggo就是代替了你手动编写yaml的部分.只要通过一个命令就可以将注释转换成文档,这让我们可以更加专注于代码. 目前swaggo主要实现了sw ...

  7. Golang使用swaggo自动生成Restful API文档

    #关于Swaggo 相信很多程序猿和我一样不喜欢写API文档.写代码多舒服,写文档不仅要花费大量的时间,有时候还不能做到面面具全.但API文档是必不可少的,相信其重要性就不用我说了,一份含糊的文档甚至 ...

  8. 使用swagger生成API文档

    有时候一份清晰明了的接口文档能够极大地提高前后端双方的沟通效率和开发效率.本文将介绍如何使用swagger生成接口文档. swagger介绍 Swagger本质上是一种用于描述使用JSON表示的RES ...

  9. Java在DOS命令下的运行及其API文档制作过程

    该文档主要描述java程序在DOS命令下的运行,以及一些常用的命令 常用DOS命令: d: 回车 盘符切换 dir(directory):列出当前目录下的文件以及文件夹 md (make direct ...

随机推荐

  1. EAS开发环境搭建.

    一:EAS开发环境安装 解压EAS服务器安装包到E盘即可,内含BOS开发环境. 二:EAS客户端安装 EAS8.0.exe安装到D盘,这是客户端. 三:远程数据库 使用远程运维系统,登陆数据库.

  2. [C#] VS2017中在某些目录下使用不了 .NET Core 2.0 问题的处理办法

    作者: zyl910 一.缘由 最近遇到了一个奇怪的问题--明明已经在VS2017里装好了 .NET Core 2.0 SDK,且测试过新建一个 .NET Core 2.0控制台项目能成功使用.但是在 ...

  3. Django 用户登陆访问限制 @login_required

    #用户登陆访问限制 from django.http import HttpResponseRedirect #只有登录了才能看到页面 #设置方法一:指定特定管理员才能访问 def main(requ ...

  4. OpenCV 对矩阵进行掩码操作

    Mask operations on matrices https://docs.opencv.org/master/d7/d37/tutorial_mat_mask_operations.html ...

  5. 【原创 Hadoop&Spark 动手实践 8】Spark 应用经验、调优与动手实践

    [原创 Hadoop&Spark 动手实践 7]Spark 应用经验.调优与动手实践 目标: 1. 了解Spark 应用经验与调优的理论与方法,如果遇到Spark调优的事情,有理论思考框架. ...

  6. Spring的两种代理方式:JDK动态代理和CGLIB动态代理

    代理模式 代理模式的英文叫做Proxy或Surrogate,中文都可译为”代理“,所谓代理,就是一个人或者一个机构代表另一个人或者另一个机构采取行动.在一些情况下,一个客户不想或者不能够直接引用一个对 ...

  7. awk按顺序去除重复行

    # root @ c7bit1 in ~ [16:43:40] $ cat test a b c d b g # root @ c7bit1 in ~ [16:46:27] C:2 $ awk '!x ...

  8. 启动matlab时总是直接跳转到安装界面的解决方案

    [关于2017双11过后MATLAB许可过期问题的解决方案] 在距离双11还有2个月之前,matlab会提示:Your MATLAB license will expire in 50 days -- ...

  9. Linux之文件系统各种符号说明

    / 根目录 唯一必须挂载的目录.不要有任何的犹豫,选一个分区,挂载它!(在绝大多数情况下,有10G的容量应该是够用了.当然了,很多东西都是多多益善的) /boot 它包含了操作系统的内核和在启动系统过 ...

  10. 火车头采集器如何采集QQ群成员中的QQ号

    如何采集QQ群群员QQ号,采集QQ号,批量采集QQ号 众所周知,QQ群群员QQ号无法导出,即使会员也不可以,那我们只能通过三方工具来实现我们的要求,那今天我们讲讲如何通过火车采集器来采集QQ群群员QQ ...