如何在 Next.js 中渲染页面之前重定向? [英] How to redirect before rendering page in Next.js?

查看:282
本文介绍了如何在 Next.js 中渲染页面之前重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 Next.js 中渲染页面之前重定向用户?

I am wondering if I can redirect a user before rendering a page in Next.js?

现在我有这个:

import { useRouter } from 'next/router';

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

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

出现此错误:错误:未找到路由器实例.你应该只使用下一个/路由器";在您的应用程序的客户端内.

谢谢.

推荐答案

你可以使用 getServerSideProps 通过在返回的对象上具有重定向"属性.

You could do it with getServerSideProps by having a 'redirect' property on the returned object.

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

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

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

I can't say if this will render the page on server or not, but the user will be redirected and not be shown the content of the redirect page.

这篇关于如何在 Next.js 中渲染页面之前重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆