Skip to content
开发文档
高级
了解 SWR

了解 SWR

¥Understanding SWR

状态机

¥State Machine

useSWR 根据 fetcher 函数的状态返回 dataerrorisLoadingisValidating。此图描述了 SWR 在某些情况下如何返回值。

¥useSWR returns data, error, isLoading, and isValidating depending on the state of the fetcher function. This diagrams describe how SWR returns values in some scenarios.

获取并重新验证

¥Fetch and Revalidate

此模式是获取数据并稍后重新验证它。

¥This pattern is to fetch data and revalidate it later.

A pattern for fetch and revalidate

键更改

¥Key Change

此模式是获取数据并更改键并稍后重新验证它。

¥This pattern is to fetch data and change the key and revalidate it later.

A pattern for key change

键更改 + 先前数据

¥Key Change + Previous Data

此模式是获取数据并更改键,并稍后使用 keepPreviousData 选项重新验证它。

¥This pattern is to fetch data and change the key and revalidate it later with the keepPreviousData option.

A pattern for key change + previous data

倒退

¥Fallback

此模式是获取数据并稍后使用回退数据重新验证它。

¥This pattern is to fetch data and revalidate it later with fallback data.

A pattern for fallback

键更改 + 回退

¥Key Change + Fallback

此模式是获取数据并更改键,然后使用后备数据重新验证它。

¥This pattern is to fetch data and change the key and revalidate it later with fallback data.

A pattern for key change + fallback

键更改 + 先前数据 + 回退

¥Key Change + Previous Data + Fallback

此模式是获取数据并更改键,并稍后使用 keepPreviousData 选项和回退数据重新验证它。

¥This pattern is to fetch data and change the key and revalidate it later with the keepPreviousData option and fallback data.

A pattern for key change + previous data + fallback

与 isLoading 和 isValidating 结合以获得更好的用户体验

¥Combining with isLoading and isValidating for better UX

与现有的 isValidating 值相比,isLoading 是一个新属性,可以帮助你处理更一般的 UX 加载情况。

¥Comparing to the existing isValidating value, isLoading is a new property that can help you for the more general loading cases for UX.

  • 每当有正在进行的请求时,无论数据是否加载,isValidating 都会变成 true

    ¥isValidating becomes true whenever there is an ongoing request whether the data is loaded or not

  • 当有正在进行的请求且数据尚未加载时,isLoading 变为 true

    ¥isLoading becomes true when there is an ongoing request and data is not loaded yet.

简单地说,你可以使用 isValidating 来指示每次正在进行重新验证,使用 isLoading 来指示 SWR 正在重新验证,但还没有数据可显示。

¥Simply saying you can use isValidating for indicating everytime there is an ongoing revalidation, and isLoading for indicating that SWR is revalidating but there is no data yet to display.

📝

回退数据和以前的数据不被视为 "加载的数据,",因此当你使用回退数据或启用 keepPreviousData 选项时,你可能有数据要显示。

¥Fallback data and previous data are not considered "loaded data," so when you use fallback data or enable the keepPreviousData option, you might have data to display.

function Stock() {
  const { data, isLoading, isValidating } = useSWR(STOCK_API, fetcher, {
    refreshInterval: 3000
  });
 
  // If it's still loading the initial data, there is nothing to display.
  // We return a skeleton here.
  if (isLoading) return <div className="skeleton" />;
 
  // Otherwise, display the data and a spinner that indicates a background
  // revalidation.
  return (
    <>
      <div>${data}</div>
      {isValidating ? <div className="spinner" /> : null}
    </>
  );
}

An example of using the isLoading state

你可以找到代码示例 此处 (opens in a new tab)

¥You can find the code example here (opens in a new tab)

返回以前的数据以获得更好的用户体验

¥Return previous data for better UX

当基于连续的用户操作进行数据请求时,例如 打字时实时搜索,保留之前获取的数据可以大大提高用户体验。keepPreviousData 是启用该行为的选项。这是一个简单的搜索 UI:

¥When doing data fetching based on continuous user actions, e.g. real-time search when typing, keeping the previous fetched data can improve the UX a lot. keepPreviousData is an option to enable that behavior. Here's a simple search UI:

function Search() {
  const [search, setSearch] = React.useState('');
 
  const { data, isLoading } = useSWR(`/search?q=${search}`, fetcher, {
    keepPreviousData: true
  });
 
  return (
    <div>
      <input
        type="text"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Search..."
      />
 
      <div className={isLoading ? "loading" : ""}>
        {data?.products.map(item => <Product key={item.id} name={item.name} />)
      </div>
    </div>
  );
}

启用 keepPreviousData 后,即使你更改 SWR 键,你仍然会获取之前的数据,并且新键的数据会再次开始加载。

¥With keepPreviousData enabled, you will still get the previous data even if you change the SWR key and the data for the new key starts loading again.

Keep previous search results when keepPreviousData has been enabled

你可以在此处找到此示例的完整代码:https://codesandbox.io/s/swr-keeppreviousdata-fsjz3m (opens in a new tab)

¥You can find the full code for this example here: https://codesandbox.io/s/swr-keeppreviousdata-fsjz3m (opens in a new tab).

性能依赖收集

¥Dependency Collection for performance

SWR 仅当组件中使用的状态已更新时才会触发重新渲染。如果你仅在组件中使用 data,SWR 会忽略其他属性(如 isValidatingisLoading)的更新。这大大减少了渲染次数。更多信息可参见 此处

¥SWR only triggers re-rendering when the states used in the component have been updated. If you only use data in the component, SWR ignores the updates of other properties like isValidating, and isLoading. This reduces rendering counts a lot. More information can be found here.