我试图创建一个结构与多个不同的布局旁边的私人路线,以显示正确的内容基于用户的登录状态和分配的布局。目前我有3个不同的布局,但我可能会添加另一个在未来。
routes.js
import React from 'react';
import { LayoutOne, LayoutTwo, LayoutThree } from './layouts';
import RouteWithLayout from './components/RouteWithLayout/RouteWithLayout';
import Login from './components/Login/Login';
import Dash from './components/Dash/Dash';
import Home from './components/Home/Home';
import NotFound from './components/NotFound/NotFound';
import ErrorBoundary from './components/ErrorBoundary/ErrorBoundary';
const Routes = () => (
<ErrorBoundary>
<Switch>
<RouteWithLayout
component={Home}
exact
layout={LayoutOne}
path="/"
isPrivate={false}
/>
<RouteWithLayout
component={Dash}
exact
layout={LayoutTwo}
path="/dash"
isPrivate={true}
/>
<RouteWithLayout
component={Login}
exact
layout={LayoutThree}
path="/login"
isPrivate={false}
/>
<Route component={NotFound}/>
</Switch>
</ErrorBoundary>
);
export default Routes;
RouteWithLayout.js
import React from 'react';
import { Route } from 'react-router-dom';
import { authService } from "./services/auth.service";
const RouteWithLayout = props => {
const { layout: Layout, component: Component, private: isPrivate, ...rest } = props;
const isLogged = authService.isLogged();
return (
<Route
{...rest}
render={matchProps =>
isPrivate ? (
isLogged ? (
<Layout>
<Component {...matchProps} />
</Layout>
) : (
<Redirect
to={{
pathname: "/login",
state: { from: matchProps.location }
}}
/>
)
) : (
<Layout>
<Component {...matchProps} />
</Layout>
)
}
/>
)
};
export default RouteWithLayout;
请记住,我这样做是正确的,还是我应该采取一些其他/更好的方法,从而简化我一直试图实现的目标?
发布于 2020-05-22 18:24:37
您可以使用多个选项来处理不同的布局。
如果您有多条共享公共布局的路线,那么您所采用的方法是很好的。
但是,如果您有许多针对不同路由的不同布局,则更好的做法是直接在各个组件中呈现Layout
,如下所示
const Dash = () => (
<LayoutOne>
{/* Dash component code */}
</LayoutOne>
)
您甚至可以对公共路由采用上面的方法,因为它更容易使用,并让Route组件做它实际做的事情。
另外,像Gatsby这样的框架实际上通过在每个页面中使用多个布局来处理多个布局,所以这是一个很好的遵循模式
https://stackoverflow.com/questions/61956725
复制相似问题