加载状态指示器 Background Fetching Indicators
查询的status === 'loading'状态足以显示查询的初始硬加载状态,但是有时你可能想显示一个额外的指示符,表明该查询正在后台重新获取数据。
为此,Query 提供了一个isFetching的布尔值,无论status变量的状态如何,你都可以使用它来表示数据正在获取中:
TypeScript
1function Todos() {2 const {3 status,4 data: todos,5 error,6 isFetching,7 } = useQuery({8 queryKey: ["todos"],9 queryFn: fetchTodos,10 });11 12 return status === "loading" ? (13 <span>Loading...</span>14 ) : status === "error" ? (15 <span>Error: {error.message}</span>16 ) : (17 <>18 {isFetching ? <div>Refreshing...</div> : null}1920 <div>21 {todos.map((todo) => (22 <Todo todo={todo} />23 ))}24 </div>25 </>26 );27}显示全局后台加载的状态
除了单个查询的加载状态外,如果要在任何查询正在获取数据时(包括在后台)都显示一个全局的加载指示器,你可以使用useIsFetchingHook:
TypeScript
1import { useIsFetching } from "@tanstack/react-query";2 3function GlobalLoadingIndicator() {4 const isFetching = useIsFetching();5 6 return isFetching ? (7 <div>Queries are fetching in the background...</div>8 ) : null;9}