【问题标题】:React Router 4: Different templates from root routeReact Router 4:来自根路由的不同模板
【发布时间】:2023-03-13 02:44:01
【问题描述】:

我一直在一个新项目中尝试使用 react router 4,我遇到的一个小问题是如何确保“子”路由不会从父路由继承。

假设我在根路由/ 有一个页面,它呈现导航和仪表板,以及显示用户配置文件的“/profile”,与根路由共享模板,但我想将用户重定向到/login,如果他们没有登录,使用 RR4 的结构,来自根路由的模板将反映在登录子路由上,我虽然有几种方法可以解决这种行为,但它们看起来都很 hacky,我想到的方法之一是使用正则表达式。

不确定最好的方法应该是什么..

<Router>
    <div>
        <Route path='/' component={() => <h1>Home Page</h1> }/>
        <Route path='/login' component={ () => <h1>Logins</h1>  }/>
        <Route path='/profile' component={ () => <h1>Profile</h1>  }/>
    </div>
</Router>

登录和个人资料都显示Home Page,但我只希望个人资料这样做。

【问题讨论】:

  • 能否包含一些代码,特别是您配置的路由?
  • 您能否展示您的子路由如何“与根路由共享模板”?
  • @MattD 请查找更新

标签: reactjs react-router react-router-v4


【解决方案1】:

我想解决此问题的一种方法是使用 HOC。比如

let template = function(WrappedComponent) {
  return class extends React.Component {
    render() {
      return (
         <h1>Home Page</h1>
         <WrappedComponent {...this.props}/>
      )
    }
  }
}

<Router>
    <div>
       <Switch>
        <Route path='/' component={ template() } exact/>
        <Route path='/login' component={ () => <h1>Logins</h1>  }/>
        <Route path='/profile' render={ template(<h1>Profile</h1> ) }/>
       </Switch>
    </div>
</Router>

【讨论】:

    【解决方案2】:

    您需要在您的 App 组件中添加一个Switch,如下所示

    <Router>
        <div>
           <Switch>
            <Route path='/' component={<HomeTemplate/>}/>
            <Route path='/login' component={ () => <h1>Logins</h1>  }/>           
           </Switch>
        </div>
    </Router>
    

    创建一个HomeTempate 组件并添加一个Switch 以及所有需要派生模板的Route

    <Header/>
    <TemplateSpecificComponents/>
    <Switch>
          <Route path='/profile' render={ () =><h1>Profile</h1> }/>
          ...
    </Switch>
    

    来自 React Router 文档 (https://reacttraining.com/react-router/web/api/Switch):

    &lt;Switch&gt; 的独特之处在于它专门呈现一条路线。相比之下,与该位置匹配的每个 &lt;Route&gt; 都会以包容性方式呈现。

    编辑:更新为在个人资料中呈现 HomeTemplate,但不在登录中。

    【讨论】:

    • 这种方法的问题是模板现在不与个人资料页面共享,我仍然想部分维护模板共享属性,同时防止它与几个页面共享
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2018-08-27
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多