Skip to content

SWR

用于数据请求的 React 钩子

轻量

即时

暂停

分页

后端无关

SSR / SSG 现成

TypeScript 现成

远程 + 本地

“SWR”这个名字来源于 stale-while-revalidate,一种由 HTTP RFC 5861 (opens in a new tab) 普及的 HTTP 缓存失效策略。SWR 是一种策略,首先从缓存返回数据(旧的),然后发送获取请求(重新验证),最后得到最新的数据。

¥The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861 (opens in a new tab). SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

使用 SWR,组件将 不断地自动地 获得数据流更新。
用户界面将始终是 快速反应式

¥With SWR, components will get a stream of data updates constantly and automatically.
And the UI will be always fast and reactive.

概述

¥Overview

import useSWR from 'swr'
 
function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)
 
  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

在此示例中,useSWR 钩子接受 key 字符串和 fetcher 函数。key 是数据的唯一标识符(通常是 API URL),将传递给 fetcherfetcher 可以是任何返回数据的异步函数,你可以使用原生 fetch 或 Axios 等工具。

¥In this example, the useSWR hook accepts a key string and a fetcher function. key is a unique identifier of the data (normally the API URL) and will be passed to fetcher. fetcher can be any asynchronous function which returns the data, you can use the native fetch or tools like Axios.

该钩子返回 3 个值:dataisLoadingerror,基于请求的状态。

¥The hook returns 3 values: data, isLoading and error, based on the status of the request.

特性

¥Features

只需一行代码,你就可以简化项目中的数据请求逻辑,并且还拥有所有这些开箱即用的惊艳特性:

¥With just one single line of code, you can simplify the logic of data fetching in your project, and also have all these amazing features out-of-the-box:

  • 快速、轻量级且可重用的数据请求

    ¥Fast, lightweight and reusable data fetching

  • 内置缓存和请求数据去重

    ¥Built-in cache and request deduplication

  • 实时体验

    ¥Real-time experience

  • 传输和协议无关

    ¥Transport and protocol agnostic

  • SSR / ISR / SSG 支持

    ¥SSR / ISR / SSG support

  • TypeScript 现成

    ¥TypeScript ready

  • React Native

SWR 为你提供速度、正确性和稳定性的各个方面的服务,帮助你打造更好的体验:

¥SWR has you covered in all aspects of speed, correctness, and stability to help you build better experiences:

  • 快速页面导航

    ¥Fast page navigation

  • 按时间间隔轮询

    ¥Polling on interval

  • 数据依赖

    ¥Data dependency

  • 聚焦时重新验证

    ¥Revalidation on focus

  • 网络恢复时重新验证

    ¥Revalidation on network recovery

  • 本地修改(Optimistic UI)

    ¥Local mutation (Optimistic UI)

  • 智能错误重试

    ¥Smart error retry

  • 分页和滚动位置恢复

    ¥Pagination and scroll position recovery

  • React Suspense

还有 更多

¥And a lot more.