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

时间:2021-03-20 16:13:36

标签: javascript node.js 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.

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用 getServerSideProps 通过在返回的对象上设置“重定向”属性来实现。

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

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

我不能说这是否会在服务器上呈现页面,但用户将被重定向并且不会显示重定向页面的内容。

答案 1 :(得分:0)

const router = useRouter();

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

return null

可能是这个作品

答案 2 :(得分:0)

使用 Router 类重定向

import Router from "next/Router"

export default function RedirectPage() {

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

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

This way you dont have to make an instance