如何在每次浏览器选项卡更改或重新加载页面时停止重新获取 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;
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>
}
如果您还有其他问题,请告诉我。