【问题标题】:How to redirect before rendering page in Next.js?如何在 Next.js 中渲染页面之前重定向?
【发布时间】:2021-03-21 08:22:42
【问题描述】:

我想知道是否可以在 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.

谢谢。

【问题讨论】:

    标签: javascript node.js next.js


    【解决方案1】:

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

    export default function RedirectPage() {
        return (
            <div><h1>hi</h1></div>
        )
    }
    
    export async function getServerSideProps(ctx) {
      return {
        redirect: {
          destination: '/projects',
          permanent: false,
        },
      }
    }
    

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

    【讨论】:

      【解决方案2】:
      const router = useRouter();
      
      useEffect(() => {
          router.push('/projects');
      },[])
      
      return null
      

      可能是这个作品

      【讨论】:

        【解决方案3】:

        使用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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-22
          • 1970-01-01
          • 1970-01-01
          • 2020-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多