框架
版本

后台抓取指示器

查询的 status === 'pending' 状态足以显示查询的初始硬加载状态,但有时您可能还想显示一个指示器,表明查询正在后台重新获取。为此,查询还为您提供了一个 isFetching 布尔值,您可以使用它来显示它处于获取状态,而不管 status 变量的状态如何:

tsx
function Todos() {
  const {
    status,
    data: todos,
    error,
    isFetching,
  } = useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  })

  return status === 'pending' ? (
    <span>加载中...</span>
  ) : status === 'error' ? (
    <span>错误:{error.message}</span>
  ) : (
    <>
      {isFetching ? <div>刷新中...</div> : null}

      <div>
        {todos.map((todo) => (
          <Todo todo={todo} />
        ))}
      </div>
    </>
  )
}
function Todos() {
  const {
    status,
    data: todos,
    error,
    isFetching,
  } = useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  })

  return status === 'pending' ? (
    <span>加载中...</span>
  ) : status === 'error' ? (
    <span>错误:{error.message}</span>
  ) : (
    <>
      {isFetching ? <div>刷新中...</div> : null}

      <div>
        {todos.map((todo) => (
          <Todo todo={todo} />
        ))}
      </div>
    </>
  )
}

显示全局后台获取加载状态

除了单个查询加载状态之外,如果您想在任何查询正在获取(包括在后台)时显示一个全局加载指示器,可以使用 useIsFetching 钩子:

tsx
import { useIsFetching } from '@tanstack/react-query'

function GlobalLoadingIndicator() {
  const isFetching = useIsFetching()

  return isFetching ? (
    <div>查询正在后台获取...</div>
  ) : null
}
import { useIsFetching } from '@tanstack/react-query'

function GlobalLoadingIndicator() {
  const isFetching = useIsFetching()

  return isFetching ? (
    <div>查询正在后台获取...</div>
  ) : null
}