问题描述
我是 React Native 的新手,我正在尝试在我的应用程序中实现本地推送通知,当我尝试使用推送通知时,出现此错误:
TypeError: _notification.default.localnotification is not a function. (In '_notification.default.localnotification()','_notification.default.localnotification' is undefined)
。
我尝试了多种选择,但仍然无法弄清楚出了什么问题。
这是我的 react-native-push-notifications 配置类:
export default class NotificationService {
constructor(onNotification) {
this.configure(onNotification);
this.lastId = 0;
}
configure(onNotification) {
PushNotification.configure({
onNotification: onNotification,permissions: {
alert: true,badge: true,sound: true
},popInitialNotification: true,});
}
localnotification() {
this.lastId++;
PushNotification.createChannel(
{
channelId: "custom-channel-id",// (required)
},);
PushNotification.localnotification({
channelId: "custom-channel-id",title: "Local Notification",message: "My Notification Message",playSound: false,soundName: 'default',actions: '["Yes","No"]'
});
}
scheduleNotification() {
this.lastId++;
PushNotification.localnotificationSchedule({
date: new Date(Date.Now() + (30 * 1000)),//30 seconds
title: "Scheduled Notification",playSound: true,});
}
checkPermission(cbk) {
return PushNotification.checkPermissions(cbk);
}
cancelNotif() {
PushNotification.cancellocalnotifications({id: ''+this.lastId});
}
cancelAll() {
PushNotification.cancelAlllocalnotifications();
}
}
和我想触发通知的班级:
import { localnotification } from '../../service/notification.service'
notif() {
localnotification();
}
.
.
.
.
<TouchableOpacity onPress={this.notif}>
<LinearGradient
style={theme.ButtonSettings}
start={{ x: 0,y: 0 }}
end={{ x: 1,y: 0 }}
colors={[theme.GRADIENT_BLUE_1,theme.GRADIENT_BLUE_2]}>
<MyText style={theme.buttonSettingsText}>zapisz</MyText>
</LinearGradient>
</TouchableOpacity>
我坐了很多小时,我不知道这是 react-native-push-notification 配置的问题,或者只是导入或 smh 的一些愚蠢错误。
解决方法
您没有在任何地方实例化您的通知服务。
你可以试试:
import { NotificationService } from '../../service/notification.service'
(顺便说一句,这是一个看起来很奇怪的导入路径,您的文件实际上是 .service
吗?)假设 notification.service
是您声明 {{1 }}
然后在组件中您想要调用该方法的某个地方,例如它是 NotificationService
方法或 constructor
方法,您将声明 componentDidMount
的实例,并传递一个 {{ 1}} 方法:
NotificationService
然后在您的 onNotification
方法中,您可以这样调用 const myNotificationService = new NotificationService(onNotification)
方法:
notif
或者,在您的 localNotification
文件中,您可以导出它的一个实例,而不是导出 notif() {myNotificationService.localNotification()}
,该实例将在您的其余代码中使用(单例模式)