我在 useEffect 钩子中执行以下代码:
const requestNotificationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
{
title: 'Notification Permission',
message: 'Allow the app to send you notifications',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('Notification permission granted');
} else {
console.log('Notification permission denied');
}
} catch (err) {
console.warn(err);
}
};
useEffect(() => {
AppState.addEventListener('change', (state) => {
if (state === 'active') {
fetchData();
}
});
requestNotificationPermission();
fetchData();
getList();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
但它的行为真的很奇怪。无需请求许可,它工作得很好,但在使用它时,fetchData() 函数会执行多次。而且权限会在没有弹出窗口或任何权限请求的情况下自动被拒绝。然后,即使我只想显示一次,我的应用程序也会因多次显示数组而被窃听。
不知道是什么问题,也上网查了一下,好像没有人有这个问题。如果我尝试使用 PushNotification.localNotification 通过本机反应发送推送通知,它会起作用,但老实说,我不知道这是否与我的问题有关。我还包含在我的 AndroidManifes.xml 中,我的 API 版本是 31 或更高。所以也许有知识的人可以帮助我