我有这段代码每 10 秒获取一次数据
useEffect(() => {
const intervalId = setInterval(() => {
setSecondsElapsed((prevSecondsElapsed) => prevSecondsElapsed + 1);
if (secondsElapsed % 10 === 0) {
// Every 10 seconds
fetchData();
}
}, 1000);
return () => clearInterval(intervalId);
}, [secondsElapsed]);
和获取方法:
const fetchData = async () => {
try {
const data = await FetchData();
setValue(data);
const newLength = data.length;
let hasNewItems = false;
if (data && newLength > prevLengthRef.current) {
console.log("New Order Received:", newLength - prevLengthRef.current,"new items added" );
hasNewItems = true;
sendNotification(expoPushToken); // Send notification
setInitialLength(newLength);
prevLengthRef.current = newLength;
} else {
console.log("No new orders received.");
}
} catch (error) {
console.error("Error:", error.message);
Alert.alert("Error", "Failed to fetch data. Please try again later.");
}
};
使用此解决方案,它无法在 Background 中工作,即使应用程序已关闭,如何设置应用程序在后台工作
要在后台获取,Expo 有一个跨平台 API