reactjs - 如何在反应原生状态下保存一个信号播放器 ID
问题描述
我是本地人的新手,我正在使用一个信号进行通知。我从OneSignal.configure();
这里获得了一个信号用户玩家 ID,并通过遵循我已经完成的代码,但该玩家 ID 我只能在控制台上看到。我正在使用setState
保存状态,但它显示错误setState is not a function
。我怎样才能让玩家 id 将其保存在状态中。
代码:
componentWillMount() {
OneSignal.init("d447e6e2-0c8e-4781-8292-6e77d2e86691");
OneSignal.configure();
OneSignal.addEventListener('received', this.onReceived);
OneSignal.addEventListener('opened', this.onOpened);
OneSignal.addEventListener('ids', this.onIds);
}
componentWillUnmount() {
OneSignal.removeEventListener('received', this.onReceived);
OneSignal.removeEventListener('opened', this.onOpened);
OneSignal.removeEventListener('ids', this.onIds);
}
onReceived(notification) {
console.log("Notification received: ", notification);
}
onOpened(openResult) {
console.log('Message: ', openResult.notification.payload.body);
console.log('Data: ', openResult.notification.payload.additionalData);
console.log('isActive: ', openResult.notification.isAppInFocus);
console.log('openResult: ', openResult);
}
onIds(device) {
console.log('Device info: ', device);
console.log('player id: ', device.userId);
this.setState({
pid: device.userId,
})
console.log(this.state.pid);
}
解决方案
事件侦听器函数不知道你的this
,所以你必须使用bind
你的this
内部。
componentWillMount() {
OneSignal.init('ONESIGNAL-APP-ID');
OneSignal.addEventListener('received', this.onReceived.bind(this));
OneSignal.addEventListener('opened', this.onOpened.bind(this));
OneSignal.addEventListener('ids', this.onIds.bind(this));
OneSignal.configure();
}
更新
您还可以声明为箭头函数以避免 .bind(this):
componentWillMount() {
OneSignal.init('ONESIGNAL-APP-ID');
OneSignal.addEventListener('received', this.onReceived);
OneSignal.addEventListener('opened', this.onOpened);
OneSignal.addEventListener('ids', this.onIds);
OneSignal.configure();
}
onReceived = () => {}
onOpened = () => {}
onIds = () => {}
推荐阅读
- python - Jupyter 实验室错误地使用基本 python 可执行文件,jupyter notebook 正确使用 venv 可执行文件?
- gooddata - 反应组件 6.0.1 中的表渲染错误
- r - Rstudio 编辑器中用于暂存和丢弃选择的按钮不起作用
- amazon-web-services - Amazon SQS FIFO 队列
- scikit-learn - 应该考虑哪种方法来评估不平衡的多类分类?
- jsp - 刷新后 JSP 不反映更改
- mongodb - 在 mongoDB 的数组中创建唯一的对象
- hyperledger-composer - 无法使用重新声明的变量打开游乐场业务网络
- php - Woocommerce 新订单自定义主题
- sql - 如何使用 group by 和 order by 获取列字段的两个连续行之间的差异