看名字就能猜出來(lái),useInfiniteQuery() 是專門(mén)用來(lái)應(yīng)付無(wú)限查詢場(chǎng)景的。不僅如此,useInfiniteQuery() API 能力也是基于 useQuery() 的。
之前的文章中我們介紹了 useQuery() 的核心 API,為了找回印象,我們?cè)诖速N出來(lái):
import { useQuery } from 'react-query'const { data, error, isError, isFetching, isLoading, isRefetching, isSuccess, refetch,} = useQuery(queryKey, queryFn?, { enabled, onError, onSuccess, refetchOnWindowFocus, retry, staleTime,})
如果我們把這些 API 簡(jiǎn)化如下:
const { ...result,} = useQuery(queryKey, queryFn?, { ...options,})
useInfiniteQuery() 其實(shí)就是在 useQuery() 基礎(chǔ)之上增添一些無(wú)限查詢場(chǎng)景的參數(shù):
const { fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, isFetchingNextPage, isFetchingPreviousPage, ...result} = useInfiniteQuery(queryKey, ({ pageParam = 1 }) => fetchPage(pageParam), { ...options, getNextPageParam: (lastPage, allPages) => lastPage.nextCursor, getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor,})
如你所見(jiàn),增加的 API 其實(shí)就是跟上一頁(yè)/下一頁(yè)查詢動(dòng)作相關(guān)的參數(shù),相比較于自己組裝 的分頁(yè)查詢能力的 useQuery(),useInfiniteQuery() 需要配置上一頁(yè)/下一頁(yè)的參數(shù)獲取函數(shù),并提供了相應(yīng)的查詢調(diào)用能力,更加自動(dòng)化和便捷。
當(dāng)然,增加的不只是參數(shù),還有 2 處:
一個(gè)是 queryFn 參數(shù)的入?yún)ⅲ嗔艘粋€(gè)名為 pageParam 的參數(shù)。
pageParam 表示當(dāng)前頁(yè)數(shù)。這個(gè)值是每次 useInfiniteQuery() 調(diào)用時(shí),通過(guò) getNextPageParam()/getPreviousPageParam() 返回值自動(dòng)獲取并傳入 queryFn 的。
第二個(gè)還有返回值的數(shù)據(jù)結(jié)構(gòu),即 data。
const { data } = useInfiniteQuery()
原來(lái) data 就是表示內(nèi)部請(qǐng)求方法的返回值。而 useInfiniteQuery() 的返回 data 因?yàn)橐囗?yè)數(shù)據(jù)(展示舊數(shù)據(jù)時(shí),還要持有舊數(shù)據(jù)),因此 data 變更為:
data: { pages: TData[], pageParams: unknown[] }
pages 很好理解,就是用來(lái)承載過(guò)程中請(qǐng)求到的多頁(yè)數(shù)據(jù);pageParams 則是每個(gè)頁(yè)面當(dāng)時(shí)在做數(shù)據(jù)獲取時(shí)使用的查詢參數(shù)。
當(dāng)然語(yǔ)言上說(shuō)得再多,也是蒼白無(wú)力的,實(shí)踐出真知。這里我們就舉一個(gè)簡(jiǎn)單的例子說(shuō)明 useInfiniteQuery() 的使用。
首先,我們先創(chuàng)建一個(gè)獲取數(shù)據(jù)的請(qǐng)求函數(shù)(使用 Fetch API)。
const getPosts = async (pageParam) => { return fetch(`https://jsonplaceholder.typicode.com/posts?_page=${pageParam.page}&_limit=${pageParam.size}`).then(res => res.json())}
接著,使用 useInfiniteQuery() 請(qǐng)求數(shù)據(jù):
function Example() { const { isLoading, isError, error, data, } = useInfiniteQuery( 'posts', ({ pageParam }) => getPosts(pageParam), { getNextPageParam: (lastPage, allPages) => ({ page: allPages.length + 1, size: 6 }), refetchOnWindowFocus: false, // Prevent refetching on window focus } ) // ...}
增加下加載中或出現(xiàn)異常時(shí)的處理邏輯。
function Example() { // ... if (isLoading) { return <div>Loading...</div>; } if (isError) { return <div>Error: {error.message}</div> } // ...}
最后渲染分頁(yè)數(shù)據(jù)。
function Example() { // ... return ( <div> <ol> {/* (1) */} {data.pages.map((page) => ( {page.map((post) => ( <li key={post.id}>{post.title}</li> ))} ))} </ol> {/* (2) */} <button onClick={() => fetchNextPage()}>More</button> </div> )}
瀏覽器訪問(wèn),不幸運(yùn)是,報(bào)錯(cuò)了。
圖片
完美。
最后,再把完整代碼貼出來(lái),方便大家學(xué)習(xí)。
import { useEffect, useRef } from 'react'import { QueryClient, QueryClientProvider, useInfiniteQuery } from 'react-query'// Create a clientconst queryClient = new QueryClient()export default function App() { return ( // Provide the client to your App <QueryClientProvider client={queryClient}> <Example /> </QueryClientProvider> )}const getPosts = async (pageParam = { page: 1, size: 25 }) => { return fetch(`https://jsonplaceholder.typicode.com/posts?_page=${pageParam.page}&_limit=${pageParam.size}`).then(res => { const total = res.headers.get('X-Total-Count') return res.json().then(data => { return { total, data, hasMore: pageParam.page * pageParam.size < total } }) })}function Example() { const { isLoading, isFetchingNextPage, hasNextPage, isError, error, data, fetchNextPage } = useInfiniteQuery( 'posts', ({ pageParam }) => getPosts(pageParam), { getNextPageParam: (lastPage, allPages) => { return lastPage.hasMore ? { page: allPages.length + 1, size: 25 } : undefined }, refetchOnWindowFocus: false, // Prevent refetching on window focus } ) const loadMoreRef = useRef(null); useEffect(() => { const observer = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && hasNextPage) { fetchNextPage(); } }); if (loadMoreRef.current) { observer.observe(loadMoreRef.current); } return () => observer.disconnect(); }, [hasNextPage, fetchNextPage]); if (isLoading) { return <div>Loading...</div>; } if (isError) { return <div>Error: {error.message}</div> } return ( <div> <p>總共 <strong>{data.pages[0].total}</strong> 條數(shù)據(jù)</p> <ol> {data.pages.map((page) => ( <> {page.data.map((post) => ( <li key={post.id}>{post.title}</li> ))} </> ))} </ol> <div className="loadMore" style={{ height: '30px', lineHeight: '30px' }} ref={loadMoreRef}> { isFetchingNextPage ? <span>Loading...</span> : <span>--- 我是有底線的 ---</span> } </div> </div> )}
本文我們講述了 React Query 中用于無(wú)限查詢 API useInfiniteQuery() 的使用。
通過(guò)循序漸進(jìn)的 3 個(gè)案例,最終實(shí)現(xiàn)了一個(gè)下拉到底后自動(dòng)新數(shù)據(jù)的交互效果,還是比較好實(shí)現(xiàn)的。
當(dāng)然,本文只是以“下一頁(yè)”舉例,“上一頁(yè)”與此同理。
希望本位講述的內(nèi)容能夠?qū)δ愕墓ぷ饔兴鶐椭8兄x閱讀,再見(jiàn)。
[1]React Query 是做什么的?: https://juejin.cn/post/7378015213348257855
[2]一個(gè)數(shù)據(jù)獲竟然被 React Query 玩出這么多花樣來(lái)!: https://juejin.cn/post/7380342160581918731
[3]React Query 的 useQuery 竟也內(nèi)置了分頁(yè)查詢支持!: https://juejin.cn/post/7380569775686746151
[4]IntersectionObserver API: https://ruanyifeng.com/blog/2016/11/intersectionobserver_api.html
本文鏈接:http://www.tebozhan.com/showinfo-26-98195-0.html如何使用 React Query 做下拉數(shù)據(jù)自動(dòng)刷新?
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: 聊聊大文件分片上傳和分片下載
下一篇: 智能個(gè)性化推薦系統(tǒng)設(shè)計(jì)與實(shí)踐,你學(xué)會(huì)了嗎?