具有多种布局的 React Router v4 [英] React Router v4 with multiple layouts

查看:30
本文介绍了具有多种布局的 React Router v4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的公共布局中渲染我的一些路线,在我的私人布局中渲染一些其他路线,有没有一种干净的方法来做到这一点?

I'd like to render some of my routes within my public layout, and some other routes within my private layout, is there a clean way to do this?

这个显然不起作用的例子,但我希望能大致解释我在找什么:

Example that obviously doesn't work, but I hope explains roughly what I'm looking for:

<Router>

  <PublicLayout>
    <Switch>
      <Route exact path="/" component={HomePage} />
      <Route exact path="/about" component={AboutPage} />
    </Switch>
  </PublicLayout>

  <PrivateLayout>
    <Switch>
      <Route exact path="/profile" component={ProfilePage} />
      <Route exact path="/dashboard" component={DashboardPage} />
    </Switch>
  </PrivateLayout>

</Router>

我想为某些路由切换布局,我该如何使用新的 react 路由器来实现这一点?

I'd like the layout to switch for certain routes, how do I do this with the new react router?

嵌套路由不再有效并给我这个错误:

Nesting routes no longer works and gives me this error:

You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

让布局包含整个路线组也意味着只要您留在同一个私人/公共路线组中,这些布局只会呈现一次.例如,如果您的布局必须从您的服务器获取某些内容,这将是一件大事,因为如果您用布局包装每个页面,那么每次页面更改时都会发生这种情况.

Having layouts wrap entire groups of routes also means those layouts are only rendered once as long as you stay in the same private/public group of routes. This is a big deal if your layout has to fetch something from your server for example, as that would happen on every page change if you wrap each page with a layout.

推荐答案

我为此所做的是创建一个简单的组件,为 Route 组件添加一个额外的属性,即布局:

What I have done for this is create a simple component that adds an extra property to the Route component which is layout:

function RouteWithLayout({layout, component, ...rest}){
  return (
    <Route {...rest} render={(props) =>
      React.createElement( layout, props, React.createElement(component, props))
    }/>
  );
}

那么在您的情况下,您的路线将如下所示

Then in your case your routes would look like this

<Switch>
    <RouteWithLayout layout={PublicLayout} path="/" component={HomePage}/>
    <RouteWithLayout layout={PublicLayout} path="/about" component={AboutPage}/>
    <RouteWithLayout layout={PrivateLayout} path="/profile" component={ProfilePage}/>
    <RouteWithLayout layout={PrivateLayout} path="/dashboard" component={DashboardPage}/>
</Switch>

这篇关于具有多种布局的 React Router v4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆