首页 > 解决方案 > Next.js 从/到另一个页面重定向

问题描述

我是Next.js的新手,我想知道如何从起始页 ( / ) 重定向到/hello-nextjs。一旦用户加载页面,然后确定路径 === /是否重定向到/hello-nextjs

react-router中,我们执行以下操作:

<Switch>
  <Route path="/hello-nextjs" exact component={HelloNextjs} />
  <Redirect to="/hello-nextjs" /> // or <Route path="/" exact render={() => <Redirect to="/hello-nextjs" />} />
</Switch>

标签: htmlreactjsroutingreact-routernext.js

解决方案


更新:Next.js >= 12
现在您可以使用中间件_middleware.js进行重定向,在 pages 文件夹(或 pages 内的任何子文件夹)中创建一个文件

import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req, ev) {
    const { pathname } = req.nextUrl
    if (pathname == '/') {
        return NextResponse.redirect('/hello-nextjs')
    }
    return NextResponse.next()
}

更新:Next.js >= 10

从 Next.js 10 开始,您可以使用内部的键进行服务器端重定向(请参见下文的客户端重定向)or :redirectgetServerSidePropsgetStaticProps

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
  // or use context.resolvedUrl for conditional redirect
  // if(context.resolvedUrl == "/")
  if (!data) {
    return {
      redirect: {
        destination: '/hello-nextjs',
        permanent: false,
      },
    }
  }

  return {
    props: {}, // will be passed to the page component as props
  }
}

注意:使用getServerSideProps将强制应用程序进行 SSR,也不支持在构建时重定向,如果重定向在构建时已知,您可以在next.config.js中添加这些重定向

next.js您可以使用ex加载页面后重定向:Router

import Router from 'next/router'

componentDidMount(){
    const {pathname} = Router
    if(pathname == '/' ){
       Router.push('/hello-nextjs')
    }
}

或使用 Hooks :

import React, { useEffect } from "react";
import Router from 'next/router'

...
useEffect(() => {
   const {pathname} = Router
   if(pathname == '/' ){
       Router.push('/hello-nextjs')
   }
 });

如果你想在重定向之前防止闪烁,你可以使用一个简单的技巧:

import React, { useEffect,useState } from "react";
import Router from 'next/router'
const myPage = ()=>{
    const [loaded,setLoaded] = useState(false)
    useEffect(() => {
        const {pathname} = Router
        // conditional redirect
        if(pathname == '/' ){
            // with router.push the page may be added to history
            // the browser on history back will  go back to this page and then forward again to the redirected page
            // you can prevent this behaviour using location.replace
            Router.push('/hello-nextjs')
           //location.replace("/hello-nextjs")
        }else{
            setLoaded(true)
        }
      },[]);

    if(!loaded){
        return <div></div> //show nothing or a loader
    }
    return ( 
        <p>
            You will see this page only if pathname !== "/" , <br/>
        </p> 
    )
}
export default myPage

我会说,当您可以使用next.config.js重定向甚至更好地使用组件的条件渲染时,通常不是一个好的/优雅的客户端重定向方法。

我在这里创建了一个包含上面所有示例的简单存储库。


推荐阅读