mcpField
N
nextjs-app-router-patterns

nextjs-app-router-patterns

github.com/wshobson开发41.9k32.9k 次安装2 周前更新
代码仓库

关于 nextjs-app-router-patterns

面向使用 App Router 构建或迁移 Next.js 14+ 应用的开发者,介绍渲染、路由与数据处理模式。

主要功能

  1. 01Server 与 Client Components
  2. 02静态、动态和流式渲染
  3. 03并行路由与拦截路由
  4. 04数据获取、缓存与 Server Actions

适用场景

  1. 01从 Pages Router 迁移
  2. 02实现 Server Components 和流式页面
  3. 03构建采用 Server Actions 的全栈功能

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshobson/agents --skill nextjs-app-router-patterns

安装后在 Claude Code 中输入/nextjs-app-router-patterns确认已加载。

附带文件references/details.md

详细介绍

Next.js App Router 模式

Next.js 14+ App Router 架构、Server Components 以及现代全栈 React 开发的综合模式。

何时使用本技能

  • 使用 App Router 构建新的 Next.js 应用
  • 从 Pages Router 迁移到 App Router
  • 实现 Server Components 与流式渲染
  • 设置并行路由与拦截路由
  • 优化数据获取与缓存
  • 使用 Server Actions 构建全栈功能

核心概念

1. 渲染模式
模式位置何时使用
Server Components仅服务端数据获取、繁重计算、密钥
Client Components浏览器交互性、hooks、浏览器 API
静态构建时很少变化的内容
动态请求时个性化或实时数据
流式渐进式大型页面、缓慢的数据源
2. 文件约定
app/
├── layout.tsx       # Shared UI wrapper
├── page.tsx         # Route UI
├── loading.tsx      # Loading UI (Suspense)
├── error.tsx        # Error boundary
├── not-found.tsx    # 404 UI
├── route.ts         # API endpoint
├── template.tsx     # Re-mounted layout
├── default.tsx      # Parallel route fallback
└── opengraph-image.tsx  # OG image generation

快速开始

// app/layout.tsx
import { Inter } from 'next/font/google'
import { Providers } from './providers'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: { default: 'My App', template: '%s | My App' },
  description: 'Built with Next.js App Router',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body className={inter.className}>
        <Providers>{children}</Providers>
      </body>
    </html>
  )
}

// app/page.tsx - Server Component by default
async function getProducts() {
  const res = await fetch('https://api.example.com/products', {
    next: { revalidate: 3600 }, // ISR: revalidate every hour
  })
  return res.json()
}

export default async function HomePage() {
  const products = await getProducts()

  return (
    <main>
      <h1>Products</h1>
      <ProductGrid products={products} />
    </main>
  )
}

详细模式与完整示例

详细的模式文档位于 references/details.md。当上述导航层级不够用时,请阅读该文件。

最佳实践

应该做的
  • 从 Server Components 开始 - 仅在需要时添加 'use client'
  • 就近放置数据获取 - 在使用数据的地方获取数据
  • 使用 Suspense 边界 - 为缓慢的数据启用流式渲染
  • 利用并行路由 - 独立的加载状态
  • 使用 Server Actions - 用于支持渐进增强的变更操作
不应该做的
  • 不要传递不可序列化的数据 - Server → Client 边界的限制
  • 不要在 Server Components 中使用 hooks - 没有 useState、useEffect
  • 不要在 Client Components 中获取数据 - 使用 Server Components 或 React Query
  • 不要过度嵌套布局 - 每个布局都会增加组件树的深度
  • 不要忽略加载状态 - 始终提供 loading.tsx 或 Suspense

评论

支持 Markdown