小编典典

使用React Router和Router

reactjs

使用 withRouter() 时如何获取路由上下文,位置,参数等?

import { withRouter } from 'react-router';

const SomeComponent = ({location, route, params}) => (
    <h1>The current location is {location.pathname}</h1>
);

const ComposedWithRouter = withRouter(SomeComponent);

您可以使用withRouter获得该信息,还是必须将这些内容显式传递到组件树中?


阅读 267

收藏
2020-07-22

共1个答案

小编典典

因此,不再使用context。在道具中都可以使用:

SomeComponent.propTypes = {
  location: React.PropTypes.shape({
    pathname: React.PropTypes.string,
    query: React.PropTypes.shape({
      ...
    })
  }),
  params: React.PropTypes.shape({
    ...
  }),
  router: React.PropTypes.object
}

const ComposedWithRouter = withRouter(SomeComponent);

因此,假设SomeComponent您想将用户转到新路线,您只需this.props.router.push('someRoute')

2020-07-22