【发布时间】:2017-11-21 01:19:56
【问题描述】:
我正在尝试在我的 React Native 应用程序中设置一个消息传递模块,它应该从服务中获取信息并以不同的方式将其呈现在不同的组件中。有点像这里的收件箱消息:您收到一条消息,在标题组件中,您会看到带有红点的收件箱和新消息的数量。如果单击它,您将转到另一个完全呈现消息的组件。
现在,我创建了两个组件来以这两种不同的方式呈现收件箱。但是当我尝试将它们链接到处理通知的类时,我在组件类中收到错误,指出对象未定义。
我有这样的事情:
存储新消息的类
class Notifications {
constructor() {
this.notifications = [];
}
receiveNotification(notif) {
this.notifications.push(notif);
}
}
let notifications = new Notifications();
export { notifications };
处理来自服务的新消息的类
import framework from 'framework'; // this is the framework I use to communicate with the service
import Notifications from './Notifications.js';
export class PushNotificator extends Component {
constructor(props) {
super(props);
this.state = {
token: ""
}
}
componentDidMount() {
framework.requestPermissions()
.then(() => console.log('granted'))
.catch(() => console.log('notification permission rejected'));
framework.getToken().then(token => {
console.log("TOKEN (getToken)", token);
this.setState({token: token});
});
this.notificationListener = framework.on(frameworkEvent.Notification, notif => {
console.log("Notification", notif);
this.showLocalNotification(notif);
})
}
showLocalNotification(notif) {
Notifications.notifications.push(notif); // this fails because Notifications is undefined
framework.presentLocalNotification({
title: notif.title,
body: notif.body,
priority: "high",
click_action: notif.click_action,
show_in_foreground: true,
local: true
});
}
componentWillUnmount() {
this.notificationListener.remove();
}
render() {
return null;
}
}
标题收件箱组件的相关部分
import Notifications from './Notifications.js' //assume the paths are correct
import {PushNotificator} from './PushNotificator.js'
export class Home extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
notifications: Notifications.notifications.find(notif => notif.seen).length
};
this.closeActivityIndicator = () => setTimeout(() => {
this.setState({ loading: false });
}, 2000);
}
...
render() {
<PushNotificator />
...
}
一旦调用构造函数,程序就会失败,因为 Notifications 未定义。但为什么它是未定义的?我不能这样用吗?
谢谢。
【问题讨论】:
标签: reactjs react-native es6-class es6-modules