“useSWR”——用于远程数据获取的 React Hooks restful-react

2025-06-08

“useSWR”——用于远程数据获取的 React Hooks

restful-react

该图片由analogicusPixabay上发布

Zeit 发布了 React hook,useSWR,它的标语是“用于远程数据获取的 React Hooks”。

SWR代表,好吧,查看网站看看它的意思(😉)。

它确实做到了它声称要做的事情,并且做得很好很轻松

“出色地”

useSWR具有以下特点。

  • 轻的
  • 后端无关
  • 即时的
  • 面向 JAMstack
  • 悬念
  • TypeScript 已准备好
  • REST兼容
  • 远程+本地

“简单的”

悬念

是的。它与React Suspense的实验频道兼容。

您需要做的就是将其设置为APIsuspense: true中的选项之一

  const { data } = useSWR(
    "https://jsonplaceholder.typicode.com/posts",
    url =>
      fetch(url)
        .then(_ => _.json())
        .then(sleep),
    { suspense: true }
  );

正在获取数据。

主页显示以下基本示例。

import useSWR from '@zeit/swr'

function Profile () {
                                               1️⃣ 👇
  const { data, error } = useSWR('/api/user', fetch)

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

在此示例中,React Hook useSWR 接受一个参数key和一个fetch函数。key 是数据的唯一标识符,通常是 API 的 URL。然后,key 将被传递给 fetch,它会异步返回数据。

我有点迷失,1️⃣ fetch因为我期望传递fetch并期望像axiosuseSWR那样自动将响应转换为 json 字符串,但事实并非如此。

因此,使用基本示例中的模式,您可能想要传递自己的方法,该方法获取数据并将其转换为 json(请参阅getRandomDog下面的方法)。

const getRandomDog = url => fetch(url).then(_ => _.json());

// https://swr.now.sh/#basic-data-loading
function BasicDataLoading() {
  const { error, data } = useSWR(
    `https://dog.ceo/api/breeds/image/random`,
    getRandomDog
  );

  return (
    <>
      {error && <p>Error! {error}</p>}
      {data && data.status === "success" && (
        <img src={data.message} alt={data.message} />
      )}
    </>
  );
}

我发现它的工作方式类似于一个函数,它接受key'/api/user'在基本示例中)参数,然后由“你”作为调用者决定如何返回值。无论是异步方法还是同步方法,在我尝试的时候都没问题。

const getCachedText = async text => text;
const options = {
  revalidateOnFocus: false,
  shouldRetryOnError: false
};
function CachedHeader() {
  const { data: cachedText } = useSWR("Cached Header", getCachedText, options);

  return <h1>{cachedText}</h1>;
}

function Identity({ value }) {
  const { data } = useSWR(value, () => value, options);

  return <>{data}</>;
}

沙盒

我创建了一个沙盒来体验和学习这个库。fork

一下,试试看 :)

注意:它使用的是 React 的实验版本(它随时可能崩溃)

告别辞

这篇帖子是在一小时内创建的,只是为了记录和分享兴奋之情🎉

查看项目页面https://swr.now.sh/了解更多信息,并在 GitHub repo https://github.com/zeit/swr了解更多信息。

鏂囩珷鏉ユ簮锛�https://dev.to/dance2die/useswr-react-hooks-for-remote-data-fetching-1nlo
PREV
你对微软收购 GitHub 有何看法?Visual Studio Code - 开源 (“Code - OSS”) TypeScript
NEXT
我的播客订阅