应用程序置于后台时获取错误

2024-01-24

我的 RN 应用程序遇到了问题,想知道是否有人遇到过这个问题以及他们是如何解决的。 在 fetch 调用期间,如果用户将应用程序置于后台并返回,则 fetch 始终会出错(catch 块)。如果您对此问题还有其他疑问,请告诉我。


最近陷入这个问题。有时,当应用程序处于后台时,iOS 上的网络请求会失败。https://developer.apple.com/forums/thread/106838 https://developer.apple.com/forums/thread/106838

您可以尝试下面的钩子,它在发送请求之前等待您的应用程序进入前台。

import { useEffect, useRef } from "react";
import { AppState, AppStateStatus } from "react-native";

export const useFetchOnAppForeground = () => {
  const listener = useRef(null);

  function fetchOnAppForeground(params) {
    if (AppState.currentState === "active") {
      return fetch(params);
    } else {
      return new Promise((resolve, reject) => {
        function fetchData(state: AppStateStatus) {
          if (state === "active") {
            console.log("calling foreground fetch");
            fetch(params).then(resolve).catch(reject);
            AppState.removeEventListener("change", fetchData);
            listener.current = null;
          }
        }

        AppState.addEventListener("change", fetchData);
        listener.current = fetchData;
      });
    }
  }

  useEffect(() => {
    return () => {
      if (listener.current) {
        AppState.removeEventListener("change", listener.current);
      }
    };
  }, []);

  return fetchOnAppForeground;
};
// Usage
const fetch = useFetchOnAppForeground();

Gist - https://gist.github.com/intergacticspacehighway/e1ec053064871f98f50646f80f99c888 https://gist.github.com/intergalacticspacehighway/e1ec053064871f98f50646f80f99c888

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

应用程序置于后台时获取错误 的相关文章

随机推荐