【问题标题】:How to identify which switch component has loaded in react-router如何识别在 react-router 中加载了哪个开关组件
【发布时间】:2019-05-27 02:38:03
【问题描述】:

我在 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 中,然后会返回组件名称?

【问题讨论】:

    标签: reactjs react-router switch-statement components react-props


    【解决方案1】:

    Layout 在 BrowserRouter 内部,这确实是可能的。

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

    export default withRouter(Layout)

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

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

    【讨论】:

      【解决方案2】:

      react-router-dom 中的BrowserRouter 使用 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>
        }
      

      【讨论】:

        猜你喜欢
        • 2021-05-15
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多