打开下拉时的React使用Query多次称为多次
我正在使用“ React-Query”来调用组件中的API。出于这个问题的目的,我正在返回API的模拟回应。
每次我打开下拉列表,都会调用使用useQuery函数,然后称为模拟API。
app.js
import React from 'react';
import './style.css';
import { QueryClient, QueryClientProvider } from 'react-query';
import { DropDown } from './Dropdown.js';
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<DropDown />
</div>
</QueryClientProvider>
);
}
下拉.js
import React from 'react';
import { useQuery } from 'react-query';
export const DropDown = () => {
console.log('DropDown re-rendered');
const { data, isLoading, isError } = useQuery('API', () => {
return new Promise((resolve, reject) => {
console.log('API called');
resolve(['mockData']);
});
});
return (
<>
<select>
<option> 1 </option>
<option> 2 </option>
</select>
</>
);
};
您可以在此处找到演示: https://react-quct-quxt-quxtxd.stackblitz.io
在控制台中,您会看到每次打开下拉列表时,都会调用usequery。
作为避免这种情况的替代方法,我可以使用传统的使用效率进行API调用,但是我正在考虑利用UseQuery提供的缓存优势,但由于此而已“重新渲染”问题。
有什么建议 /修改吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对我
有用:
如果所有您的查询都需要此配置。最好将其添加到您的QueryClient的
defaultOptions
This works for me
Usage:
If all your queries need this config. It's good to add this to
defaultOptions
of your queryClient看来原始的Stackblitz已经固定了,因此问题不再可再现。对于后代:
由于将窗口聚焦,您可能已经看到了背景。这是因为
staletime
默认为0
和refetchonwindowfocus
默认值为true
。您可以关闭标志,也可以设置更高的staletime
(建议)。It seems that the original stackblitz has been fixed, so the issue is no longer reproducible. For posterity:
You've probably seen a background refetch due to focusing the window. This is because
staleTime
defaults to0
andrefetchOnWindowFocus
defaults totrue
. You can either turn off the flag, or set a higherstaleTime
(recommended).