我在反应本机博览会推送通知时遇到问题 我的应用程序的主要目标是从谷歌工作表文件中获取数据并显示它 在此代码中,我有 fetch 方法,每 20 秒检查一次添加的新项目是否更新数据
const fetchData = async () => {
setIsFetching(true);
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");
await sendNotification(expoPushToken);
hasNewItems = true; // Set flag if new items found
setInitialLength(newLength);
prevLengthRef.current = newLength;
} else {
console.log("No new orders received.");
}
// }
} catch (error) {
console.error("Error:", error.message);
}
在此代码中,它每 20 秒执行一次该函数
fetchData(); // Initial fetch
const intervalId = setInterval(fetchData, 20000); // Fetch data every 20 seconds
return () => clearInterval(intervalId);
}, []);
这是发送通知的功能
const sendNotification = async () => {
try {
console.log("Sending push notification...");
// notification message
const message = {
to: expoPushToken,
sound: "default",
title: "New Order ",
body: "Open the app new order received 🚀",
};
await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
host: "exp.host",
accept: "application/json",
"accept-encoding": "gzip, deflate",
"content-type": "application/json",
},
body: JSON.stringify(message),
});
console.log("Notification sent successfully!");
} catch (error) {
console.error("Error sending notification:", error);
Alert.alert("Error", "Failed to send notification");
}
};
当我将函数放入按钮中时它就起作用了
<Button title="Send push notification" onPress={sendNotification} />
空的依赖数组意味着效果不依赖于组件范围中的任何值。因此,它应该只在初始渲染后运行一次,而不是在任何后续渲染中运行。