繁体   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