如何从我的应用程序的任何地方访问当前路线?

How to access current route from anywhere in my app?

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

React Router provides singleton versions of history (browserHistory and hashHistory) that you can import and use from anywhere in your application.

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

如何访问当前的路线位置?

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

You can get access to the history object's properties and the closest Route's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

它的用法是这样的:

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