如何使用react-query停止在页面加载时重新获取数据

问题描述 投票:0回答:1
我有一个react-js页面。我正在使用 React 查询从 API 获取数据。我想将第一次页面访问时来自 API 的数据存储在缓存中,之后总是从缓存中读取数据。

如何在每次浏览器选项卡更改或重新加载页面时停止重新获取 API 请求?

我的组件代码是这样的

import { useQuery } from 'react-query'; const QueryCache = () => { const { data, isLoading, isFetching, isStale } = useQuery('yourQueryKey', async () => { const response = await fetch('https://jsonplaceholder.typicode.com/todos'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }, ); console.log({isFetching, isLoading}) // console.log('Cached data:', data); console.log("isStale is ", isStale); // if (isLoading) { // // Data is being initially fetched // return <p>Loading...</p>; // } // if (isFetching) { // // Data is being refetched from the cache // return <p>Fetching updated data...</p>; // } // else { // return <p>Fetching updated data...</p>; // } // Render your component with the fetched data return ( <div> { isLoading ? <>Loading...</> : <> { isFetching ? <>Notun data</> : <>Purono data</> } </> } <h1>Data:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }; export default QueryCache;
    
javascript reactjs react-query
1个回答
0
投票
您可以设置

staleTime: Infinity

cacheTime: Infinity
 ,这将在刷新时停止重新获取,并设置 
refetchOnWindowFocus: false
 来获取选项卡更改时的数据。

官方文档:

https://tanstack.com/query/v4/docs/react/guides/window-focus-refetching

修改后的代码:

const QueryCache = () => { const { data, isLoading, isFetching, error } = useQuery('yourQueryKey', async () => { const response = await fetch('https://jsonplaceholder.typicode.com/todos'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }, { staleTime: Infinity, // Data never gets stale cacheTime: Infinity, // Data remains in the cache indefinitely });

=> 在您要创建这样的实例的位置添加refetchOnWindowFocus: false


const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, // default: true }, }, }) function App() { return <QueryClientProvider client={queryClient}>...</QueryClientProvider> }
如果您还有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.