N Next.js 中文
原文 ↗
Next.js 文档/Guides / 指南/Client-side data fetching / 客户端数据获取

如何使用 SWR 获取客户端数据

使用 SWR 获取客户端数据,可选择从服务器组件提供初始数据,并协调服务器缓存和客户端缓存。

更新于 2026-10-15Next.js 16.4.6

使用 SWR 在客户端组件中获取数据,从服务器组件提供初始数据,并协调浏览器端的变更与缓存的服务器数据。请参阅客户端数据获取以选择一种模式。

在客户端获取数据

当初始视图可以等待水合后的浏览器请求时,SWR 可以完全在浏览器中获取数据。根据加载 UI 应出现的位置,选择内联或 Suspense 加载状态。在这些示例中,query 初始为空,并在水合后从客户端状态更新。

当组件应自行渲染加载和错误状态时,使用 useSWR。条件 key 会将请求延迟到交互提供输入之后:

app/product-autocomplete.tsxtsx
'use client'

import useSWR from 'swr'

type Product = { id: string; name: string }

async function fetcher(url: string): Promise<Product[]> {
  const response = await fetch(url)
  if (!response.ok) throw new Error('Failed to fetch products')
  return response.json()
}

export function ProductAutocomplete({ query }: { query: string }) {
  const {
    data = [],
    error,
    isLoading,
  } = useSWR(
    query ? `/api/products?query=${encodeURIComponent(query)}` : null,
    fetcher
  )

  if (!query) return null
  if (error) return <p>Failed to load products.</p>
  if (isLoading) return <p>Loading products...</p>

  return (
    <ul>
      {data.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  )
}

使用 Suspense 处理客户端数据

当最近的 Suspense 边界应定义加载 UI 时,使用 suspense: true。将交互式外壳保持在边界之外,使其在结果加载期间仍然可用:

app/product-autocomplete.tsxtsx
'use client'

import { Suspense } from 'react'
import useSWR from 'swr'

type Product = { id: string; name: string }

async function fetcher(url: string): Promise<Product[]> {
  const response = await fetch(url)
  if (!response.ok) throw new Error('Failed to fetch products')
  return response.json()
}

export function ProductAutocomplete({ query }: { query: string }) {
  if (!query) return null

  return (
    <Suspense fallback={<p>Loading products...</p>}>
      <ProductResults query={query} />
    </Suspense>
  )
}

function ProductResults({ query }: { query: string }) {
  const { data } = useSWR(
    `/api/products?query=${encodeURIComponent(query)}`,
    fetcher,
    { suspense: true }
  )

  return (
    <ul>
      {data.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  )
}

使用无条件 key 时,SWR 会在 Suspense 解析后定义 data。使用最近的错误边界处理请求错误。

当请求正在运行且没有可显示的已加载数据时,isLoading 的值为 true。只要请求正在运行(包括后台重新验证),isValidating 的值就是 true。

使用 suspense: true 时,Suspense 会处理初始的无数据状态。之后对同一 key 的重新验证会继续渲染当前数据,而不会再次显示 Suspense 回退内容。使用 isValidating 提供后台刷新反馈。详细了解 SWR 加载状态。

了解更多:SWR 数据获取。

须知:

当独立的 Suspense 读取在兄弟组件中渲染时,它们可以并行开始。一个组件中的多个 Suspense 读取会按顺序运行。详细了解网络瀑布和 SWR Suspense。

从服务器组件提供初始数据

当初始渲染需要数据且 SWR 应继续在浏览器中管理数据时,使用服务器提供数据模式。在 SWR 2.3.0 和 React 19 中,服务器组件可以在客户端接管之前提供回退数据。

将 <SWRConfig> 的作用域限定为拥有该数据的路由段。该 Provider 使 fallback 靠近其使用方,并避免将功能数据添加到共享布局中:

TypeScript

app/products/[id]/page.tsxtsx
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'

export default function Page({ params }: PageProps<'/products/[id]'>) {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      {params.then(({ id }) => (
        <ProductData id={id} />
      ))}
    </Suspense>
  )
}

function ProductData({ id }: { id: string }) {
  return (
    <SWRConfig
      value={{
        fallback: {
          // Not awaited: only components that read this key suspend
          [productCache.key(id)]: getProduct(id),
        },
      }}
    >
      <ProductView id={id} />
    </SWRConfig>
  )
}

JavaScript

app/products/[id]/page.jsjsx
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // some server-side function
import { productCache } from './product-cache'
import { ProductView } from './product-view'

export default function Page({ params }) {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      {params.then(({ id }) => (
        <ProductData id={id} />
      ))}
    </Suspense>
  )
}

function ProductData({ id }) {
  return (
    <SWRConfig
      value={{
        fallback: {
          // Not awaited: only components that read this key suspend
          [productCache.key(id)]: getProduct(id),
        },
      }}
    >
      <ProductView id={id} />
    </SWRConfig>
  )
}

fallback 和客户端组件必须使用相同的 SWR key。只定义一次该 key,使两个调用位置共享同一标识:

TypeScript

app/products/[id]/product-cache.tsts
export const productCache = {
  key: (id: string) => `/api/products/${id}`,
}

JavaScript

app/products/[id]/product-cache.jsjs
export const productCache = {
  key: (id) => `/api/products/${id}`,
}

在页面示例中,由 params.then() 返回的 Promise 会使 fallback 保持可见,直到路由参数解析完成。随后,ProductData 会创建一个单独的、未 await 的 getProduct(id) Promise 供 SWR fallback 使用。React 会通过 React Server Component payload 传递该 Promise,而读取匹配 key 的组件会挂起,直到数据解析完成。

客户端组件使用相同的 key 通过 useSWR 读取数据:

TypeScript

app/products/[id]/product-view.tsxtsx
'use client'

import useSWR from 'swr'
import { productCache } from './product-cache'

type Product = { id: string; name: string }

async function fetcher(url: string): Promise<Product> {
  const response = await fetch(url)
  if (!response.ok) throw new Error('Failed to fetch product')
  return response.json()
}

export function ProductView({ id }: { id: string }) {
  const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })

  return <h1>{data.name}</h1>
}

JavaScript

app/products/[id]/product-view.jsjsx
'use client'

import useSWR from 'swr'
import { productCache } from './product-cache'

async function fetcher(url) {
  const response = await fetch(url)
  if (!response.ok) throw new Error('Failed to fetch product')
  return response.json()
}

export function ProductView({ id }) {
  const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })

  return <h1>{data.name}</h1>
}

须知:

fallback 键和 useSWR 键必须完全一致。如果两者出现偏差,SWR 会忽略回退值,并在客户端执行获取。

fallback 提供该 hook 的初始值。默认情况下,SWR 会将回退数据视为已过期,并在水合后启动浏览器端重新验证。

SWR 不为回退数据提供基于时间的新鲜度窗口。当该 hook 携带缓存数据挂载时,设置 revalidateIfStale: false 会跳过重新验证。与 TanStack Query 的 staleTime 不同,此设置适用于每次挂载。

聚焦、重新连接、轮询以及 mutate 仍可重新验证该键。如需定时刷新,请设置 refreshInterval。

SWR 键指向一个带有 GET 方法的 路由处理器。路由处理器可以调用提供回退值的同一个 getProduct 函数,而浏览器则使用该 URL 进行重新验证和轮询。

了解更多:SWR 参数与键 和 SWR 与 Next.js App Router。

使用 Cache Components 缓存服务器提供的数据

在使用此模式之前,请在 next.config.ts 中启用 cacheComponents。然后,你可以缓存用作 SWR 回退值的服务器数据。添加 use cache,选择一个 cacheLife 配置,并应用 cacheTag,以便变更操作可以使其失效:

TypeScript

app/products/[id]/data.tsts
import { cacheLife, cacheTag } from 'next/cache'

export async function getProduct(id: string) {
  'use cache'
  cacheLife('max')
  cacheTag(`product:${id}`)

  const product = await db.product.findUnique({ where: { id } })
  if (!product) throw new Error('Product not found')
  return product
}

JavaScript

app/products/[id]/data.jsjs
import { cacheLife, cacheTag } from 'next/cache'

export async function getProduct(id) {
  'use cache'
  cacheLife('max')
  cacheTag(`product:${id}`)

  const product = await db.product.findUnique({ where: { id } })
  if (!product) throw new Error('Product not found')
  return product
}

此示例使用 cacheLife('max'),因为写入操作会使 product 标签失效。在缓存配置中,stale 控制 Next.js 客户端缓存可复用预取负载的时长,而 revalidate 和 expire 控制服务器缓存。当服务器值需要随时间刷新时,请选择较短的配置。

SWR 拥有独立的浏览器缓存,因此其重新验证选项无需与 cacheLife 一致。

当同一个变更操作更新浏览器缓存并使缓存的服务器数据失效时,你可以在一个共享契约中定义这两个标识:

app/products/[id]/product-cache.tsdiff
 export const productCache = {
   key: (id: string) => `/api/products/${id}`,
+  tag: (id: string) => `product:${id}`,
 }
app/products/[id]/product-cache.jsdiff
 export const productCache = {
   key: (id) => `/api/products/${id}`,
+  tag: (id) => `product:${id}`,
 }

随后,服务器函数可以调用 cacheTag(productCache.tag(id))。请确保此契约不包含 server-only 和 client-only 导入,以便两个缓存层都能复用它。

变更后协调服务器和客户端缓存

回退值提供初始值。水合后,SWR 会管理浏览器缓存和重新验证。对于复用的数据,请将 SWR 键和服务器标签保留在同一个缓存契约中:

TypeScript

app/activity/activity-cache.tsts
export const activityCache = {
  key: '/api/activity/unread',
  tag: (userId: string) => `activity:${userId}`,
}

JavaScript

app/activity/activity-cache.jsjs
export const activityCache = {
  key: '/api/activity/unread',
  tag: (userId) => `activity:${userId}`,
}

请为回退值、客户端组件读取和变更操作使用同一个键。使用 SWR 时,将写入操作传递给 mutate 并提供 optimisticData。SWR 会立即显示乐观值,并在写入失败时将其回滚。此示例在操作成功后保留乐观值,因为最终值是已知的:

TypeScript

app/activity/mark-read-button.tsxtsx
'use client'

import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'

export function MarkReadButton() {
  const { mutate } = useSWRConfig()

  function markRead() {
    return mutate(
      activityCache.key,
      async () => {
        await markActivityReadAction()
        return { count: 0 }
      },
      {
        optimisticData: { count: 0 },
        revalidate: false,
        rollbackOnError: true,
        throwOnError: false,
      }
    )
  }

  return <button onClick={markRead}>Mark read</button>
}

JavaScript

app/activity/mark-read-button.jsjsx
'use client'

import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'

export function MarkReadButton() {
  const { mutate } = useSWRConfig()

  function markRead() {
    return mutate(
      activityCache.key,
      async () => {
        await markActivityReadAction()
        return { count: 0 }
      },
      {
        optimisticData: { count: 0 },
        revalidate: false,
        rollbackOnError: true,
        throwOnError: false,
      }
    )
  }

  return <button onClick={markRead}>Mark read</button>
}

服务器操作会写入数据库,并通过 updateTag 使带标签的服务器数据失效。使用 cacheTag 为缓存的服务器查询打上标签,使标签保持匹配:

TypeScript

app/activity/actions.tsts
'use server'

import { updateTag } from 'next/cache'
import {
  getCurrentUserId,
  markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'

export async function markActivityReadAction() {
  const userId = await getCurrentUserId()
  await markActivityReadInDatabase(userId)
  updateTag(activityCache.tag(userId))
}

JavaScript

app/activity/actions.jsjs
'use server'

import { updateTag } from 'next/cache'
import {
  getCurrentUserId,
  markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'

export async function markActivityReadAction() {
  const userId = await getCurrentUserId()
  await markActivityReadInDatabase(userId)
  updateTag(activityCache.tag(userId))
}

乐观的 SWR 值会更新当前屏幕。updateTag 确保下一次对缓存的服务器读取会返回最新的活动数据。

值得了解:

当服务器操作更改了必须立即反映该写入的缓存读取时,请调用 updateTag。未缓存的读取没有可更新的服务器标签。有关其他失效行为,请参阅客户端数据获取。

查看在线 next-spa-patterns 演示及其源代码。进一步了解 SWR 变更与乐观更新以及 SWR 文档。

相关指南和参考。

  • 获取数据:了解如何获取数据并流式渲染依赖数据的部分内容。
  • SPA:Next.js 完全支持构建单页应用(SPA)。
  • 缓存:了解如何在 Next.js 中缓存数据和 UI
  • use cache:了解如何使用 "use cache" 指令在 Next.js 应用中缓存数据。
  • route.js:route.js 特殊文件的 API 参考。
  • updateTag:updateTag 函数的 API 参考。