reactjs - 使用 React Router 和 Router

标签 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);

您可以使用 withRouter 获取该信息吗?还是必须将这些信息显式地传递到组件树中?

最佳答案

所以,不再使用context。这一切都可以在 Prop 中找到:

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

关于reactjs - 使用 React Router 和 Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174814/

相关文章:

javascript - react-redux-i18n 切换语言

node.js - node-sass 错误部署 react 到 Elastic Beanstalk

javascript - React - 从 API 收到 401 响应后保留表单信息

通过调用 browserHistory 测试异步 redux 操作

javascript - 使用 redux 和 react 的异步服务器端渲染

javascript - 如何使用正则表达式来约束 ReactJS 路由

react-router - 在 onEnter 中使用 replaceState 时 this.props.location.state 为 null

javascript - 正在编辑 Redux 状态而不派发任何操作

reactjs - 为什么Ant设计中没有 `<Input>`的onchange

javascript - react : Is it possible to call a higher-order component within a container component?