簡體   English   中英

如何在 Next.js 中渲染頁面之前重定向?

[英]How to redirect before rendering page in Next.js?

我想知道在 Next.js 中呈現頁面之前是否可以重定向用戶?

現在我有這個:

import { useRouter } from 'next/router';

export default function RedirectPage() {
    const router = useRouter();
    router.push('/projects');

    return (
        <div><h1>hi</h1></div>
    )
}

出現此錯誤: Error: No router instance found. you should only use "next/router" inside the client side of your app. Error: No router instance found. you should only use "next/router" inside the client side of your app.

謝謝。

您可以通過在返回的 object 上使用“重定向”屬性來使用getServerSideProps來實現。

export default function RedirectPage() {
    return (
        <div><h1>hi</h1></div>
    )
}

export async function getServerSideProps(ctx) {
  return {
    redirect: {
      destination: '/projects',
      permanent: false,
    },
  }
}

我不能說這是否會在服務器上呈現頁面,但用戶將被重定向並且不會顯示重定向頁面的內容。

const router = useRouter();

useEffect(() => {
    router.push('/projects');
},[])

return null

可能是這個工作

使用路由器 class 重定向

import Router from "next/Router"

export default function RedirectPage() {

    Router.push({
       pathname: '/projects'
    })

    return (
        <>Redirecting ....</>
    )
}

This way you dont have to make an instance

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM