不确定两个完全独立的共享布局是否有优点,但会尝试解决您的问题。我将创建一个共享上下文和单一布局工厂,根据您的规则返回相关布局,即用户存在等。
将布局包装在 _app.js 中的 Context 中:
function MyApp({ Component, pageProps, router }: MyAppProps) {
return (
<UserProvider>
<Layout>
<Component {...pageProps} key={router.asPath} />
</Layout>
</UserProvider>
);
}
然后在 Layout 中访问上下文并呈现适当的选项:
// context
import { useUser } from '../utils/user';
import Header from './header';
import AuthenticatedHeader from './header/authenticated';
interface LayoutProps {
children: any;
}
const DefaultLayout = ({ children }: LayoutProps) => {
return (
<>
<Header />
{children}
</>
);
};
const AuthLayout = ({ children }: LayoutProps) => {
return (
<>
<AuthenticatedHeader />
{children}
</>
);
};
const Layout = ({ children }: LayoutProps) => {
const { user } = useUser();
return (
<>
{/* conditionally render appropriate */}
{user ? <AuthLayout>{children}</AuthLayout> : <DefaultLayout>{children}</DefaultLayout>}
</>
);
};
export default Layout;
代码沙盒