使用 React Router 和路由器 [英] Using React Router withRouter

查看:61
本文介绍了使用 React Router 和路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you get the routing context, location, params, etc, when using withRouter()?

import { withRouter } from 'react-router';

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

const ComposedWithRouter = withRouter(SomeComponent);

你能否使用 withRouter 获取这些信息,或者这些事情必须明确地传递到组件树下吗?

Can you obtain that info using withRouter or do these things have to be explicitly passed down the component tree?

推荐答案

所以,不再使用 context.这一切都在道具中可用:

So, no using context anymore. It's all available in the props:

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')

So then lets say in SomeComponent you wanted to send the user to a new route, you simply do this.props.router.push('someRoute')

这篇关于使用 React Router 和路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆