我像平常一样将用户发送到主页,它有一个事件侦听器,其中包含将用户发送到另一个屏幕的数据。然后我的路由器返回主页,用户陷入无限循环,发送通知数据并无限循环发送它们。
使用:
"expo": "~51.0.17",
"expo-notifications": "~0.28.9",
我有一个在触发器上重复的预定通知
async function scheduleWeeklyNotification() {
try {
const notificationScheduled = await AsyncStorage.getItem('weeklyTopNotificationScheduled');
if (notificationScheduled !== 'true') {
await Notifications.scheduleNotificationAsync({
content: {
title: "Flavrite",
body: "Here's some trending new products for you to rate, review ... and hopefully taste.",
data: { screen: 'WeeklyTop' },
},
trigger: {
// seconds: 5, // 5 seconds
weekday: 7, // 1 is Sunday, 7 is Saturday
hour: 11, // 11 AM
minute: 0,
repeats: true // This ensures it repeats every week
},
});
await AsyncStorage.setItem('weeklyTopNotificationScheduled', 'true');
}
} catch (error) {
console.error('Error scheduling notification:', error);
}
}
然后在我的 useEffect 中我让它转到不同的页面
useEffect(() => {
registerForPushNotificationsAsync()
.then((token) => setExpoPushToken(token ?? ''))
.catch((error) => setExpoPushToken(`${error}`));
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
const data = response.notification.request.content.data;
if (data.screen == 'WeeklyTop') {
navigation.navigate('WeeklyTop');
}
if (data.product) {
navigation.navigate('ShowFlava', { item: data.id });
}
console.log("Notification response:", response.notification.request.content.data.screen);
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
因此,在导航转到 WeeklyTop 后,它是一个滑动器,然后将导航重置到再次运行的主页,并将该用户发送回 Weekly Top 屏幕
如此重复无限循环。即使我将导航移动到另一个屏幕,它仍然陷入无限循环。
您可以使用状态来避免循环。更好的方法是使用 ID 来发送消息。
无论如何,我会将状态添加到主屏幕:
const [hasNavigated, setHasNavigated] = useState(false);
然后在你的useEffect中使用它:
const data = response.notification.request.content.data;
if (!hasNavigated) {
if (data.screen == 'WeeklyTop') {
navigation.navigate('WeeklyTop');
setHasNavigated(true);
}
if (data.product) {
navigation.navigate('ShowFlava', { item: data.id });
setHasNavigated(true);
}
console.log("Notification response:", response.notification.request.content.data.screen);
}
还将 hasNaviged 添加到依赖项数组中,例如:
…}, [hasNavigated]);
那么您只需在主屏幕聚焦时重置状态即可 u2028
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
setHasNavigated(false);
});
return unsubscribe;
}, [navigation]);
我希望这个快速修复有帮助。