教程 > next.js 中文教程 > 阅读:657

next.js 浅层路由——迹忆客-ag捕鱼王app官网

什么是浅层路由

在 next.js 中,浅层路由允许我们更改 url 而无需再次运行数据获取方法,包括 getserversideprops、getstaticprops 和 getinitialprops。

要启用浅层路由,需要将 shallow 选项设置为 true。 考虑以下示例:

更新 pages 目录中的 index.js 文件,如下所示。

index.js

 import router from 'next/router'
 import head from 'next/head'
 
 function homepage(props) {
    return (
       <>
          
             welcome to 迹忆客 - next.js 教程!
          
          
welcome to 迹忆客 - next.js 教程!
router.push('/?counter=1', undefined, { shallow: true })}>reload
next stars: {props.stars}
) } 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 /workspace/node/nextjs
> next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled client and server successfully in 453 ms (124 modules)

在浏览器中打开 localhost:3000 ,然后单击 reload 链接,将看到以下输出。

nextjs 浅层路由

查看笔记

扫码一下
查看教程更方便
网站地图