SuperAPI AI 工具集

nextjs-server-components

前端与建站

查看项目

更新于 10-16 08:48

技能介绍

用途:在 Next.js App Router 中决定何时使用 React Server Components(RSC)、何时使用 Client Component,并正确划分子组件边界。优先级 P0(关键)。注意:若项目使用 pages/ 目录而非 App Router,应完全忽略本技能。

主要能力与工作流(Add Server/Client Component Split):

  1. 默认使用 RSC——用异步 Server Component 直接取数据。
  2. 把 'use client' 下推到叶子节点——仅交互叶子节点(Button、Form、Chart)使用;布局与页面保持为 Server Component,以最大化 RSC 收益。
  3. 通过 children 组合——将 Server Component 作为 children 传给 Client Component。
  4. 序列化 props——Server 到 Client 的 props 必须可序列化(不能是函数、Date 或 Class)。
  5. 守卫密钥——在含敏感逻辑的模块中 import server-only。

实现要点:

  • 异步 RSC:在异步 Server Component 中直接 fetch,例如 await db. 查询、用 await params 取路由段。
  • 数据获取:用 cache: 'no-store' 或 revalidate: 0 退出静态渲染。
  • 流式渲染:把慢的异步组件包进 <Suspense>;用 loading.tsx 做路由级骨架。
  • 水合:服务端发送 HTML + RSC payload;客户端仅水合 Client Component。Server Component 在客户端 bundle 中零 JS。
  • Server-in-Client:不能把 Server Component import 进 Client Component;修正方式是作为 children prop 传入。

反模式:

  • 不在 Client Component 中放密钥;用 server-only 包防止意外打包。
  • 不把完整数据库对象传给客户端;尽量减少序列化 props,可能时只传 ID。
  • 不在 Server Component 中使用 useState/useEffect(这两个是 Client Component 专属 hooks)。
  • 不在组件树根部写 'use client';应把边界下推到叶子组件。

其他约束:保持 server-only 环境变量不带前缀,且不要向客户端 bundle 暴露。本技能还包含 Server/Client 组合示例与 server-boundary 检查清单可供参考。