gpt4 book ai didi

reactjs - 具有多种布局的 React Router v4

转载 作者:行者123 更新时间:2023-12-03 12:57:56 25 4
gpt4 key购买 nike

我想在我的公共(public)布局中渲染一些路线,并在我的私有(private)布局中渲染一些其他路线,有没有一种干净的方法可以做到这一点?

示例显然不起作用,但我希望大致解释我正在寻找的内容:

<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 路由器执行此操作?

嵌套路由不再有效并给出此错误:

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

编辑:让布局包含整个路由组也意味着只要您处于同一私有(private)/公共(public)路由组中,这些布局就只会呈现一次。例如,如果您的布局必须从服务器获取某些内容,那么这是一件大事,因为如果您用布局包装每个页面,那么每次页面更改都会发生这种情况。

最佳答案

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

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

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

<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>

关于reactjs - 具有多种布局的 React Router v4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42862028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com