Tia*_*mas 2 push-notification react-native expo
当应用程序运行或在后台但应用程序关闭时,我使用反应本机博览会和推送通知工作正常。它不会调用处理通知的方法。我需要重定向到详细信息页面。我尝试使用函数组件和类组件,尝试迁移到旧通知和新通知。
import React, {useState, useEffect, useRef} from 'react';
import {
Image, ScrollView,
StyleSheet, Text, TouchableOpacity, Platform,
View, Linking,
} from 'react-native';
import * as Notifications from "expo-notifications";
const HomeScreen = (props) => {
useEffect(() => {
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
const {request, date} = notification ||{}
const {content} = request ||{}
const {data} = content ||{}
const {annKey,type} = data ||{}
if(annKey) {
// navigation.navigate('Detail', {annKey, updateFeed: true, onSelect},)
}
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
const {notification} = response ||{}
console.log(notification);
const {request, date} = notification ||{}
const {content} = request ||{}
const {data} = content ||{}
const {annKey, type} = data ||{}
if(annKey){
navigation.navigate('Detail', {annKey, updateFeed: true, onSelect},)
}
});
return () => {
Notifications.removeNotificationSubscription(notificationListener);
Notifications.removeNotificationSubscription(responseListener);
};
}, []);
}
export default HomeScreen;
Run Code Online (Sandbox Code Playgroud)
小智 9
问题是useEffect()在应用程序完成初始化后调用 get 太晚了。因此,在系统放弃通知之前不会添加侦听器,并且不会调用处理程序。
幸运的是,由于您使用的是新expo-notifications库,因此它引入了useLastNotificationResponse()React hook。它可以替换addNotificationResponseReceivedListener()侦听器并返回用户与之交互的最后一个通知(即点击)。它可以安全地用在useEffect()钩子上。
以下是如何使用它(最好在根组件上实现它):
import * as Notifications from 'expo-notifications';
export default function App() {
const lastNotificationResponse = Notifications.useLastNotificationResponse();
React.useEffect(() => {
if (
lastNotificationResponse &&
lastNotificationResponse.notification.request.content.data['someDataToCheck'] &&
lastNotificationResponse.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER
) {
// navigate to your desired screen
}
}, [lastNotificationResponse]);
return (
/*
* your app
*/
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6847 次 |
| 最近记录: |