NextJS教程

Next.js 浅层路由

在 Next.js 中,浅层路由是指导航到同一页面但不调用 getServerSideProps、getStaticProps 和 getInitialProps 方法。
为了进行浅层路由,我们使用 Router 的浅层标志为 true。请参阅以下示例。
更新 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 http://localhost: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,然后单击 Reload 链接,您将看到以下输出。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4