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 }.

  1. import React, { PropTypes } from 'react'
  2. import { withRouter } from 'react-router'
  3. // 一个可以展示当前地址路径名的简单组件
  4. class ShowTheLocation extends React.Component {
  5. static propTypes = {
  6. match: PropTypes.object.isRequired,
  7. location: PropTypes.object.isRequired,
  8. history: PropTypes.object.isRequired
  9. }
  10. render() {
  11. const { match, location, history } = this.props
  12. return (
  13. <div>You are now at {location.pathname}</div>
  14. )
  15. }
  16. }
  17. // Create a new component that is "connected" (to borrow redux
  18. // terminology) to the router.
  19. const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

重要提醒

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: 如果你正在使用

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

See this guide for more information.