重定向到Next.js应用程序目录中的另一个服务器端页面。

huangapple go评论65阅读模式
英文:

Redirect to another page server-side in the app directory of Next.js

问题

我有一个在Next.js应用程序中的服务器渲染页面,我想检查一个条件并重定向到另一个页面。请查看下面的代码以更好地理解:

// 这是一个服务器渲染的页面
export default async function Packs() {
  const cookiesStore = cookies()
  const token = cookiesStore.get('token')?.value
  const gameInfo = await getGameInfo()
  const user = await getUserContextFromToken(token || "") as UserContext
  const theme = getThemeForLevel(user?.level || 1)
  if (isEmpty(user)) {
    // 与其发送主页,我们应该能够重定向
    return <HomePage sessionExpired={true} user={null} theme={theme} totalLevels={gameInfo.totalLevels} />
    // return NextResponse.redirect(AppRoutes.home, 302); // (是否有可能这样做)
  }
  return (
    <PacksPage theme={theme} currentLevel={user.level} packSize={gameInfo.packSize} totalLevels={gameInfo.totalLevels} />
  );
}
英文:

I have a server-rendered page in a Next.js application and I want to check a condition and redirect to another page. See the code below to understand better:

// This is a server-rendered page
export default async function Packs() {
  const cookiesStore = cookies()
  const token = cookiesStore.get(&#39;token&#39;)?.value
  const gameInfo = await getGameInfo()
  const user = await getUserContextFromToken(token || &quot;&quot;) as UserContext
  const theme = getThemeForLevel(user?.level || 1)
  if (isEmpty(user)) {
    // Instead of sending the home page we should be able to redirect
    return &lt;HomePage sessionExpired={true} user={null} theme={theme} totalLevels={gameInfo.totalLevels} /&gt;
    // return NextResponse.redirect(AppRoutes.home, 302); // (is something like this possible)
  }
  return (
    &lt;PacksPage theme={theme} currentLevel={user.level} packSize={gameInfo.packSize} totalLevels={gameInfo.totalLevels} /&gt;
  );
}

答案1

得分: 1

你可以使用redirect函数来自next/navigation,示例如下:

// app/page.js

import { redirect } from 'next/navigation';

export default async function Page() {
  const res = await fetch('https://...')
  if (!res.ok) {
    redirect('/login')
  }
 
  // ...
}
英文:

You can use the redirect function from next/navigation, as an example like so:

// app/page.js

import { redirect } from &#39;next/navigation&#39;

export default async function Page() {
  const res = await fetch(&#39;https://...&#39;)
  if (!res.ok) {
    redirect(&#39;/login&#39;)
  }
 
  // ...
}

huangapple
  • 本文由 发表于 2023年7月24日 00:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76749395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定