【问题标题】:How to access current route from anywhere in my app?如何从我的应用程序中的任何位置访问当前路线?
【发布时间】:2018-06-21 02:40:31
【问题描述】:

我正在尝试获取有关非路由组件上当前路由的信息。

React Router 提供单例版本的历史(browserHistory 和 hashHistory),您可以从您的任何地方导入和使用 应用。

以前,您似乎可以使用browserHistory,但似乎不再受支持。我正在使用react-router-redux^4.0.8@types\react-router-redux^5.0.1

如何访问当前路线位置?

【问题讨论】:

    标签: reactjs redux react-router react-router-redux


    【解决方案1】:

    这很简单。您可以使用withRouter HOC

    您可以访问历史对象的属性和最近的 Route 通过 withRouter 高阶组件匹配。带路由器 将更新的匹配、位置和历史道具传递给包装的 组件无论何时呈现。

    它是这样使用的:

    import {withRouter} from "react-router-dom"
    @withRouter
    class NonRouteComponent extends Component {
      render() {
        // you have access to this.props.match
        // you have access to this.props.history
        // you have access to this.props.location
        const { match, location, history } = this.props
    
        return <h1>Hi {location.pathname}</h1>;
      }
    }
    

    如果你不使用装饰器,也就是@withRouter,你可以像这样导出组件:

    class NonRouteComponent extends Component { ... }
    export default withRouter(NonRouteComponent);
    

    【讨论】:

    • 我编辑了我的答案。你应该从 react-router-dom 导入它
    • 谢谢!奖励问题:我如何在Route 上传递其他信息,例如。它应该与应用程序的哪个区域相关联?我希望能够根据区域将路线组合在一起。
    • @im1dermike 我建议使用这样的东西: 然后 AdminRoutes 将有另一个 Switch 并且可能为您的所有管理路由布局。
    猜你喜欢
    • 2017-06-07
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2011-04-18
    • 2014-09-14
    • 1970-01-01
    • 2011-01-07
    • 2019-06-22
    相关资源
    最近更新 更多