使用React Router和Router

塔比富朱达

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

import { withRouter } from 'react-router';

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

const ComposedWithRouter = withRouter(SomeComponent);

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

马修·赫伯斯特(Matthew Herbst)

因此,不再使用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')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章