react-router中如何识别加载了哪个switch组件

How to identify which switch component has loaded in react-router

我在 React 中有一个路由系统,以及一个包装该系统的 Layout 组件。 我想弄清楚如何找出在我的布局组件中选择了哪个路由组件

ReactDOM.render(
<BrowserRouter>
    <Layout>

            <Switch>
                <Route exact strict path={"/home"} component={home} />
                <Route exact path={"/page1"} component={page1} />
                <Route exact path={"/page2"} component={page2} />
                <Route exact path={"/page3"} component={page3}/>
                <Route exact path={"/page4"} component={page4}/>

            </Switch>

    </Layout>
    </BrowserRouter>
,document.getElementById('root'));

有什么方法可以按照 this.props.children.selectedRoute 在我的 Layout Component 中 return 组件名称?

LayoutBrowserRouter里面,这确实是可能的。

您所要做的就是将 Layout 组件包装在 withRouter 高阶组件中。

export default withRouter(Layout)

然后,在 Layout 中,您可以访问路由器属性,location

function Layout({ location }) {
  if(location.pathname==="page1") {
    // Do something
  } else {
    // Other cases
  }
}

BrowserRouter in react-router-dom 使用 React 上下文将路由器上下文传递到组件树中。

了解查看的路由的一种简洁方法是让 Layout 挂钩到提供的路由器上下文中。 您可以通过为 Layout 组件声明 contextTypes 属性 来完成此操作,如下所示。

class Layout extends React.Component {
  static contextTypes = {
    router: PropTypes.object
  };

  render() {
    // Get the current path
    const { route: { location: { pathname } } } = this.context.router;
    const { children } = this.props;

    // Find child route that match current path.
    // This assumes that all routes are current children of the Layout, 
    // with a Switch use `children.props.children` instead of `children`
    // to find the selected route.
    const selectedRoute = children
                           .filter(route => route.props.path === pathname)
                           .pop();
    // continue play.

    return <div>{children}</div>
  }