英文:
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('token')?.value
const gameInfo = await getGameInfo()
const user = await getUserContextFromToken(token || "") as UserContext
const theme = getThemeForLevel(user?.level || 1)
if (isEmpty(user)) {
// Instead of sending the home page we should be able to redirect
return <HomePage sessionExpired={true} user={null} theme={theme} totalLevels={gameInfo.totalLevels} />
// return NextResponse.redirect(AppRoutes.home, 302); // (is something like this possible)
}
return (
<PacksPage theme={theme} currentLevel={user.level} packSize={gameInfo.packSize} totalLevels={gameInfo.totalLevels} />
);
}
答案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 'next/navigation'
export default async function Page() {
const res = await fetch('https://...')
if (!res.ok) {
redirect('/login')
}
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论