- Next.js 教程
- Next.js - 主頁
- Next.js - 概述
- Next.js - 環境設定
- Next.js 功能
- Next.js - 頁面
- Next.js - 靜態檔案服務
- Next.js - 元資料
- Next.js - CSS 支援
- Next.js - 全域性 CSS 支援
- Next.js - 預渲染
- Next.js 路由
- Next.js - 路由
- Next.js - 動態 API 路由
- Next.js - 命令式路由
- Next.js - 淺路由
- Next.js API 路由
- Next.js - API 路由
- Next.js - API 中介軟體
- Next.js - 響應助手
- Next.js 雜項
- Next.js - Typescript
- Next.js - 環境變數
- Next.js - 部署
- Next.js - CLI
- Next.js 實用資源
- Next.js - 快速指南
- Next.js - 實用資源
- Next.js - 討論
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,然後單擊重新載入連結,您將看到以下輸出。
廣告