首页 > 解决方案 > 如何在 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.

谢谢。

标签: javascriptnode.jsnext.js

解决方案


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

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

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

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


推荐阅读