Skip to content

Next.js 常用函数与方法总结 ​

API 篇(上) ​

1. fetch ​

  • 介绍
    • 扩展原生 fetch,支持缓存控制
    • 服务端组件中可使用 async/await
  • options.cache
    • force-cache(默认):优先从缓存读取
    • no-store:每次请求都重新获取,不缓存
  • options.next.revalidate
    • false:无限期缓存
    • 0:不缓存
    • number:缓存 n 秒
  • options.next.tags
    • 设置缓存标签,配合 revalidateTag 使用

2. cookies ​

  • 介绍
    • 读取/写入 cookie
    • 动态函数,导致路由动态渲染
  • 方法
    • get(name):获取单个 cookie
    • getAll(name?):获取所有匹配 cookie
    • has(name):判断是否存在
    • set(name, value, options):设置 cookie
    • delete(name):删除 cookie

3. headers ​

  • 介绍
    • 读取请求头,只读
    • 动态函数
  • 方法
    • get(), has(), getAll(), forEach() 等
    • 继承 Web Headers API

4. NextRequest ​

  • 介绍
    • 扩展 Request API
  • cookies
    • set, get, getAll, delete, has, clear
  • nextUrl
    • 扩展 URL API,支持 pathname, searchParams

5. NextResponse ​

  • 介绍
    • 扩展 Response API
  • 方法
    • json(data, options):返回 JSON 响应
    • redirect(url):重定向
    • rewrite(url):重写 URL(不改变地址栏)
    • next():继续中间件执行

6. redirect ​

  • 介绍
    • 服务端重定向(307)
    • 可用于服务端组件、Server Actions
  • 参数
    • path: 目标路径
    • type: replace(默认)或 push

7. permanentRedirect ​

  • 介绍
    • 永久重定向(308)
  • 参数同 redirect

8. notFound ​

  • 介绍
    • 抛出 404 错误
    • 需配合 not-found.js 使用

9. useParams ​

  • 介绍
    • 客户端 Hook,获取动态路由参数
  • 返回值
    • 对象:{ slug: 'xxx' } 或 { slug: ['a', 'b'] }

10. usePathname ​

  • 介绍
    • 获取当前 pathname
  • 返回值
    • 字符串,如 /dashboard

11. useRouter ​

  • 介绍
    • 客户端路由控制
  • 方法
    • push, replace, back, forward
    • refresh, prefetch

12. useSearchParams ​

  • 介绍
    • 获取查询参数
  • 返回值
    • URLSearchParams 实例
    • 支持 get, has, getAll 等
  • 行为
    • 静态渲染:触发客户端渲染(需 Suspense)
    • 动态渲染:服务端可用

API 篇(下) ​

1. generateStaticParams ​

  • 介绍
    • 构建时生成静态路径(替代 getStaticPaths)
  • 用法
    • 返回对象数组:[{ id: '1' }, { id: '2' }]
  • 参数
    • 支持 options.params(父子段传参)
  • 返回值
    • 根据路由结构返回对应格式

2. generateViewport ​

  • 介绍
    • 自定义 viewport 元信息
  • 方式
    • 静态 viewport 对象
    • 动态 generateViewport 函数
  • 字段
    • themeColor, colorScheme, width, initialScale

3. revalidatePath ​

  • 介绍
    • 按路径重新验证缓存
  • 参数
    • path: 路径字符串
    • type: 'page' 或 'layout'
  • 注意
    • 不立即生效,下次访问时触发

4. revalidateTag ​

  • 介绍
    • 按标签重新验证缓存
  • 配合
    • fetch(..., { next: { tags: ['blog'] } })
  • 用途
    • 精细控制缓存失效

5. unstable_cache ​

  • 介绍
    • 缓存函数执行结果
  • 参数
    • fetchData: 异步函数
    • keyParts: 缓存键
    • options: tags, revalidate
  • 返回
    • 可调用的缓存函数

6. unstable_noStore ​

  • 介绍
    • 禁用缓存,强制动态渲染
  • 等价于
    • fetch(..., { cache: 'no-store' })
  • 优点
    • 比 dynamic = 'force-dynamic' 更细粒度

7. useSelectedLayoutSegment ​

  • 介绍
    • 获取当前布局下一级的路由段
  • 用途
    • 导航高亮、Tab 切换
  • 返回值
    • 字符串或 null

8. useSelectedLayoutSegments ​

  • 介绍
    • 获取当前布局下所有路由段
  • 与 Segment 区别
    • 返回数组,包含所有层级
  • 用途
    • 面包屑导航