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

问题描述 投票: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 isAuthenticated = await sleep(); //Checking...

    if (!isAuthenticated) {
        redirect("/app/login");
        // or
        // return <div>unauthorized</div>;
    }

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

loading.jsx(客户端组件)

export default function LoadPage() {
    return <div>Validating 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.