gpt4 book ai didi

reactjs - 尝试根据当前 session 加载部分主应用程序布局时出现 SSR 警告

转载 作者:行者123 更新时间:2023-12-03 20:49:53 27 4
gpt4 key购买 nike

我有一个使用 Next.Js 构建的管理仪表板。基本上,我想做这样的事情:

  • 用户从 /login 登录路线
  • 在处理登录时,显示加载屏幕
  • /路由,如果用户存在,它会加载应用程序或者如果用户丢失,重定向回登录

  • 我正在尝试这样做: _app.js :
    ...
    <Head>
    <title>My App</title>
    </Head>

    <ApolloProvider>
    <AppLayout>
    <Component {...pageProps} />
    </AppLayout>
    </ApolloProvider>
    ...
    AppLayout.js :
    ...
    // If there's no user and we are not in any of the session routes (login or forgot-password), redirect the user to login
    useEffect(() => {
    if (!(user.id) && !(router.pathname === '/login' || router.pathname === '/forgot-password')) {
    Router.push('/login').then();
    }
    });

    // While the user login process is happening, show a loading screen.
    if (
    isLoading ||
    ((user.id) && (router.pathname === '/login' || router.pathname === '/forgot-password'))
    ) {
    return <Loading />;
    }

    // If the user is there, show the admin panel
    if (user.id) {
    return (
    <>
    <Sidebar />

    <Layout>
    <TopMenu />

    {children}
    </Layout>
    </>
    );
    }

    // If no user and we are in the session routes, show the session forms without the main app layout
    if (router.pathname === '/login' || router.pathname === '/forgot-password') {
    return <>{children}</>;
    }

    // For everything else, show an empty div
    return <div />;
    ...
    现在这有效。用户登录并加载应用程序。如果未登录,则无法访问该应用程序。但用户只存在于前端。存储在全局状态(由 Mobx 管理)。它在服务器中加载的页面与它在浏览器中加载的页面不同。因此,该应用程序会引发如下错误:
    Warning: Expected server HTML to contain a matching <section> in <section>
    所以我的问题是,如何在不破坏 Next.Js 的情况下处理这样的情况?由于我们正在处理 _app.js文件,打破这个可以禁用整个应用程序的 SSR 对吗? 🤔

    最佳答案

    您需要将某种用途的 id 存储在客户端和服务器都可以访问的地方。
    一种常见的选择是将其存储在 JWT 中的 cookie 中,并使用此 token 在双方发出“auth”请求,如果登录,“auth”请求将返回用户详细信息,否则将返回明智的重定向。
    在我的应用程序中,我已经“禁用”了我的管理应用程序的 SSR,因为它不需要 SEO。

    关于reactjs - 尝试根据当前 session 加载部分主应用程序布局时出现 SSR 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63421607/

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