1

我正在使用 React-native 和 React-query,我想在卸载屏幕时停止自动重新获取。

目前,当我转到目标屏幕时,我使用间隔参数调用查询:

const { data: mission } = useMissionFetcher(missionSelectedId, 5000)

使用MissionFetcher:

export const useMissionFetcher = (idMission: string, interval: number): QueryResult<MissionMobile> => {
    const missionsQueryFn = () => getMission(idMission)
        return useQuery([QueryKeys.mission, idMission], missionsQueryFn, {
          ...baseReactQueryConfig,
          refetchInterval: interval,
        })
  }

基本反应查询配置:

export const baseReactQueryConfig = {
    refetchOnWindowFocus: false,
    staleTime: Infinity,

退出屏幕时如何停止重新获取?

4

3 回答 3

0

在 react-native 中管理焦点重新获取是不同的。道具refetchOnWindowFocus取决于window哪个仅限网络。

您正在寻找的是AppState - 这就是 React Native 管理屏幕active/状态的方式。inactive

因此,您可以通过处理这些事件来更改 react-query 重新获取的行为。参考这里:https ://react-query.tanstack.com/guides/window-focus-refetching#managing-focus-in-react-native

于 2021-01-14T16:12:41.927 回答
0

我认为您使用导航来退出当前屏幕,并且不会卸载屏幕。使用navigation.replace并且您的反应查询重新获取将自动停止,因为它将被垃圾(或者如果您愿意,可以卸载)

于 2021-01-15T09:58:22.273 回答
0

如果你只想在你聚焦屏幕时重新获取,因为很多人都想这样做,我想你可以使用这个钩子

export const useRefetchOnFocus = (refetch = () => {}, canRefetch = true) => {
  const [isScreenFocused, setIsScreenFocused] = useState(false);
  useFocusEffect(() => {
    setIsScreenFocused(true); // when i focus the screen
    return () => setIsScreenFocused(false); // when i quit the screen
  });

  /* the screen still always active in cache so we need to check that the screen is focused in a use effect
  to dispatch the refetch only one time to avoid the infinity loop*/
  useEffect(() => {
    if (isScreenFocused && canRefetch) {
      refetch();
    }
  }, [canRefetch, isScreenFocused, refetch]);
};

在你的屏幕上

  const { data, refetch } = useAccount();

  useRefetchOnFocus(refetch);
于 2021-08-25T20:12:33.103 回答