React组件内部的嵌套路由

埃德尔·萨蒂克

我正在搜索,但找不到正确的答案。是否可以在React Component中使用像这样的React Router;

import { Route, Switch } from 'react-router'    
import LandingLayout from '../../layouts/landing/LandingLayout'
import AppLayout from '../../layouts/app/AppLayout'

<Switch>
  <LandingLayout>
    <Route path="/" exact="true" component={Home} />
    <Route path='/login' component={Login} />
    <Route path='/signup' component={Signup} />
  </LandingLayout>
  <AppLayout>
    <Route path='/dashboard' component={DashboardPage} />
    <Route path='/users' component={UserList} />
    <Route path='/u/:username' component={AccountPage} />
  </AppLayout>
  <Route component={NotFound} />
</Switch>
埃德尔·萨蒂克

经过大量研究,我为我的案件找到了正确的答案。

首先,我的React应用程序是服务器渲染的应用程序。第二; 由于性能相关的问题,我正在使用React Router Switch。

由于我的应用程序架构,上述解决方案不适用于我,并且出现了一些错误,例如;

您不应在同一路径中使用Route组件和Route子代;路线孩子将被忽略

所以在这里; 我想使用具有多种布局的React Router Switch。这是如何做到的。

首先,您将创建一个自定义路由器组件,该组件将布局和组件结合在一起。说“ AppRouter”

const AppRouter = ({ component: Component, layout: Layout, ...rest }) => (
   <Route {...rest} render={props => (
     <Layout>
       <Component {...props} />
     </Layout>
   )} />
)

第二; 对于公共和私人路线,必须有两个不同的布局包装器

const LandingRouteLayout = props => (
  <div>
    <LandingLayout {...props}/>
  </div>
)

const AppRouteLayout = props => (
 <div>
   <AppLayout {...props}/>
 </div>
)

持续; 路线

const Routes = () => {
  return (
    <Switch>
      <AppRoute exact path="/" layout={LandingRouteLayout} component={Home} />
      <AppRoute path="/login" layout={LandingRouteLayout} component={Login} />
      <AppRoute path="/signup" layout={LandingRouteLayout} component={Signup} />
      <AppRoute path="/t/:token" layout={AppRouteLayout} component={SetToken} />
      <AppRoute path='/dashboard' layout={AppRouteLayout} component={DashboardPage} />
      <AppRoute path="/u/:username" layout={AppRouteLayout} component={AccountPage} />
      <Route component={NotFound} />
    </Switch>
  )
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章