【问题标题】:react-router getting this.props.location in child componentsreact-router 在子组件中获取 this.props.location
【发布时间】:2016-09-27 18:24:55
【问题描述】:

据我了解,<Route path="/" component={App} /> 将提供App 路由相关的道具,例如locationparams。如果我的App 组件有许多嵌套的子组件,我如何让子组件在没有这些道具的情况下访问这些道具:

  • 从 App 传递道具
  • 使用窗口对象
  • 为嵌套子组件创建路由

我以为this.context.router 会有一些与路线相关的信息,但this.context.router 似乎只有一些操作路线的功能。

【问题讨论】:

  • 在App Component中,直接嵌套子组件可以在this.props.children找到

标签: javascript reactjs react-router


【解决方案1】:

(更新)V5.1 和 Hooks(需要 React >= 16.8)

您可以在组件中使用useHistoryuseLocationuseRouteMatch 来获取matchhistorylocation

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

  return (
    <div>{location.pathname}</div>
  )
}

export default Child

(更新)V4 和 V5

您可以使用withRouter HOC 来在您的组件道具中注入matchhistorylocation

class Child extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

(更新)V3

您可以使用withRouter HOC 来在组件道具中注入routerparamslocationroutes

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

原答案

如果不想使用道具,可以使用React Router documentation中描述的上下文

首先,您必须设置您的childContextTypesgetChildContext

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

然后,您将能够使用这样的上下文访问子组件中的位置对象

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }

【讨论】:

  • 感谢您的指点。我没有阅读文档的那部分。我以为只有context.router
  • 我是 React 新手。因此,如果我错了,请原谅我,但是使用 window.location.pathname 有什么问题?
  • window.location 是可变的,因此最好不要访问它,最好使用不可变版本。另外,我认为可以使用与 window.location 不同的逻辑位置(至少在 nextjs 中是这样),因此可以从路由器获取与直接窗口历史记录不同的位置
  • @ArturBarseghyan 如果 React 代码在服务器上运行,则 window 对象不存在,例如实现服务器端路由。
【解决方案2】:

如果上述解决方案不适合您,您可以使用import { withRouter } from 'react-router-dom';


使用这个你可以将你的子类导出为 -

class MyApp extends Component{
    // your code
}

export default withRouter(MyApp);

还有你的路由器类 -

// your code
<Router>
      ...
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>

【讨论】:

    猜你喜欢
    • 2019-03-24
    • 2018-04-28
    • 2017-08-05
    • 1970-01-01
    • 2016-11-05
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多