Next.js - 淺路由



在 Next.js 中,淺路由是指導航到同一頁面,但不呼叫 getServerSideProps、getStaticProps 和 getInitialProps 方法。

要進行淺路由,我們使用淺標誌為 true 的 Router。請參見以下示例。

在 pages 目錄中更新 index.js 檔案,如下所示。

import Router from 'next/router'
import Head from 'next/head'

function HomePage(props) {
   return (
      <>
         <Head>
            <title>Welcome to Next.js!</title>
         </Head>
         <div>Welcome to Next.js!</div>
         <span onClick={() => Router.push('/?counter=1', undefined, { shallow: true })}>Reload</span>
         <br/>
         <div>Next stars: {props.stars}</div>
         <img src="/logo.png" alt="TutorialsPoint Logo" />
      </>	    
   )
}

export async function getServerSideProps(context) {
   const res = await fetch('https://api.github.com/repos/vercel/next.js')
   const json = await res.json()
   return {
      props: { stars: json.stargazers_count }
   }
}

export default HomePage

啟動 Next.js 伺服器

執行以下命令啟動伺服器 −.

npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next

ready - started server on https://:3000
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

驗證輸出

在瀏覽器中開啟 localhost:3000,然後單擊重新載入連結,您將看到以下輸出。

Home page with Shallow Routing
廣告