我的 RN 应用程序遇到了问题,想知道是否有人遇到过这个问题以及他们是如何解决的。 在 fetch 调用期间,如果用户将应用程序置于后台并返回,则 fetch 始终会出错(catch 块)。如果您对此问题还有其他疑问,请告诉我。
最近陷入这个问题。有时,当应用程序处于后台时,iOS 上的网络请求会失败。 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();
要点 - https://gist.github.com/intergacticspacehighway/e1ec053064871f98f50646f80f99c888
为此,您可以使用包名称 react-native-background-actions
这是链接: https://www.npmjs.com/package/react-native-background-actions
即使应用程序进入后台,这也将有助于继续获取过程