我知道这是一个愚蠢的问题,但相信我,状态没有更新,我不知道为什么,我尝试了几个小时,但它仍然总是一样,下面是我的简单 useEffect :
const [notificationData, setNotificationData] = useState(null);
useEffect(() => {
messaging().getInitialNotification().then(remoteMessage => {
if(remoteMessage){
console.log("this is remove message", remoteMessage)
setNotificationData(remoteMessage?.notification.body)
}
})
}, [])
这里我需要的只是设置NotificationData,并且我需要在我的视图中显示notification.body文本,但它只是不更新。 这是我在你问之前已经核实过的事情,
remoteMessage?.notification.body 有值吗?是的,我 100% 是这样 有价值,即使我尝试使用静态值而不是 RemoteMessage?.notification.body,它仍然相同,没有得到 已更新。
我是否在 getInitialNotification 承诺之外尝试过?是的,如果我在承诺之外设置NotificationData,当我直接在 useEffect 中设置状态时,它工作得很好。
我想知道,无论如何,它是由于任何行为或 firebbase 的通知承诺状态更改不起作用。
确保您在正确的位置使用它,我在我的本机组件(底部选项卡导航器)中使用它
rnfirebase 检查添加步骤,不要忘记 console.firebase 中的 google-services.json 文件
useEffect(() => {
const unsubscribe = messaging().onMessage(async notification => {
console.log('this onMessage', notification);
});
try {
messaging().onNotificationOpenedApp(remoteMessage => {
if (remoteMessage) {
console.log('this onNotificationOpenedApp', remoteMessage);
}
});
messaging().setBackgroundMessageHandler(remoteMessage => {
console.log('this setBackgroundMessageHandler', remoteMessage);
});
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log('this getInitialNotification', remoteMessage);
}
});
} catch (error) {
console.log('this catch error messaging', error);
}
return unsubscribe;
}, []);
此代码适用于我的项目
我希望我有用并且祝你好运🤞