打开下拉时的React使用Query多次称为多次

发布于 2025-01-26 22:56:05 字数 1636 浏览 1 评论 0 原文

我正在使用“ 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。

Stackblitz编辑器URL:

作为避免这种情况的替代方法,我可以使用传统的使用效率进行API调用,但是我正在考虑利用UseQuery提供的缓存优势,但由于此而已“重新渲染”问题。

有什么建议 /修改吗?

I am using "react-query" to call an API from a component . For the purpose of this question , I am returning a mock response from the API .

Every time , I open the dropdown , the useQuery function is called which in turn calls the mock 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>
  );
}

Dropdown.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>
    </>
  );
};

You can find the demo here : https://react-quxtxd.stackblitz.io

In the console you will see that every time you open the dropdown , useQuery is called.

Stackblitz Editor url : https://stackblitz.com/edit/react-quxtxd?file=src/Dropdown.js

As an alternative to avoid this , I can use the traditional useEffect to make the API calls but I was looking at leveraging the caching advantage that useQuery provides but I am stuck due to this "re-rendering" issue .

Any suggestions / modifications ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的位置 2025-02-02 22:56:05

这对我

{ refetchOnWindowFocus: false }

有用:

const { data, status } = useQuery("users", fetchUsers, { 
    refetchOnWindowFocus: false 
});

如果所有您的查询都需要此配置。最好将其添加到您的QueryClient的 defaultOptions

// App.tsx

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
    },
  },
});

<QueryClientProvider client={queryClient}>
...
</QueryClientProvider>

This works for me

{ refetchOnWindowFocus: false }

Usage:

const { data, status } = useQuery("users", fetchUsers, { 
    refetchOnWindowFocus: false 
});

If all your queries need this config. It's good to add this to defaultOptions of your queryClient

// App.tsx

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
    },
  },
});

<QueryClientProvider client={queryClient}>
...
</QueryClientProvider>
纸伞微斜 2025-02-02 22:56:05

看来原始的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 to 0 and refetchOnWindowFocus defaults to true. You can either turn off the flag, or set a higher staleTime (recommended).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文