使用带路由器的React路由器

Tab*_*dah 10 reactjs react-router

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

import { withRouter } from 'react-router';

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

const ComposedWithRouter = withRouter(SomeComponent);
Run Code Online (Sandbox Code Playgroud)

您可以使用withRouter获取该信息,还是必须在组件树中明确传递这些内容?

Mat*_*bst 14

所以,不再使用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);
Run Code Online (Sandbox Code Playgroud)

那么就让我们说SomeComponent你希望将用户发送到一条新路线,你只需这样做this.props.router.push('someRoute')