refetchIntervalInBackground 不会阻止带有 refetchInterval 的查询在后台重新获取

refetchIntervalInBackground does not stop a query with refetchInterval from refetching in background

我正在尝试 运行 定期进行查询,但不会在页面失焦时进行查询。

正如我从 react-query 的 API (https://react-query.tanstack.com/reference/useQuery) 中了解到的那样,我需要做的就是向查询添加一个 refetchIntervalInBackground 标志以停止在背景:

refetchIntervalInBackground: boolean Optional If set to true, queries that are set to continuously refetch with a refetchInterval will continue to refetch while their tab/window is in the background

但是,当我散开页面焦点时,此标志不会阻止查询更新。

这是我的代码(在 https://codesandbox.io/s/epic-shtern-n7jo9?file=/src/index.tsx 上 运行 也可用):

import React from "react";
import ReactDOM from "react-dom";

import { QueryClient, QueryClientProvider, useQuery } from "react-query";

const App = () => {
  const newQuestionsQuery = useQuery("new", () => new Date().toLocaleString(), {
    refetchInterval: 1000,
    refetchIntervalInBackground: false
  });

  return <div>{newQuestionsQuery.data}</div>;
};

const queryClient = new QueryClient();

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

无论页面是否获得焦点,此代码 运行 都是查询。

我是不是遗漏了什么明显的东西?如何禁止查询在后台更新(window 未聚焦)?

将焦点转移到另一个 tab/window/app 不足以让 'react-query' 认为该应用程序处于非活动状态,需要确保它 不可见,所以当我打开 devtools window 时,它仍然被认为是活动的,因为它是可见的。要测试不活动行为,请分离开发工具 window,并隐藏应用程序,在这种情况下网络请求将停止:

TkDodo: we use the provided focusManager, which listens to the visibilitychange and focus events of the browser. The browser emits those if you switch to a different tab. But I've seen these events not being emitted when I have two windows next to each other and I just focus the other window, because then it's not in the "background".

if that behaviour doesn't suit your case, you can always override the events of the focusManger, and refetchIntervalInBackground will adhere to this.

完整讨论:https://github.com/tannerlinsley/react-query/issues/2953