Nextjs 14.如何在重定向后重新渲染服务器组件

问题描述 投票:0回答:1

所以基本上我有一些服务器组件来获取数据并显示它。但只有当用户授权时才会显示:

function FirstServerComponent() {
  const isAuth = // checking if user authorized

  return (
    <div>
      {isAuth ? (
        <SecondServerComponent/>
      ): (
        <p>unauthorized</p>
      )}
    </div>
  );
}

在我的页面标题中有一个按钮,用于启动 oauth 授权流程,然后重定向回我们的页面并将我们的

isAuth
状态设置为 true。

那么我如何重新渲染

FirstServerComponent
才能渲染
SecondServerComponent

typescript next.js render react-server-components
1个回答
0
投票

为此,您将使用两件事:

NextJS - 路由重定向

NextJS - 加载 UI 和流媒体

这是一个用法示例:

文件夹结构

app
   [route]
      component/server-component.jsx
      page.jsx
      loading.jsx

page.jsx(服务器组件)

"use server";

import { redirect } from "next/navigation";
import { SecondServerComponent } from "./component";

function sleep() {
    return new Promise((resolve) => {
        setTimeout(() => resolve(true), 2000);
    });
}

export default async function Page() {
    const isAuthenticate = await sleep();

    if (!isAuthenticate) {
        redirect("/app/login");
    }

    return (
        <div>
            <SecondServerComponent />
        </div>
    );
}

loading.jsx(客户端组件)

export default function LoadPage() {
    return <div>Validing User</div>;
}

server-component.jsx(服务器组件)

export async function SecondServerComponent() {
    return <div>Server Component {String(typeof window === "undefined")}</div>;
}
© www.soinside.com 2019 - 2024. All rights reserved.