firebase - 优雅地处理通知响应 - React Native
问题描述
我试图在 React Native(0.55.4)中设置通知,我使用反应导航来渲染我的屏幕。一切都设置好了,我正在接收通知并且能够读取有效负载
我参考了以下页面以了解如何收到响应 -
https://rnfirebase.io/docs/v5.xx/notifications/receiving-notifications
我想知道如何合并它,以便在收到通知时在我的反应导航的任何页面中调用一个事件,或者在后台调用它并根据有效负载进行处理。
目前它仅在构造函数和 ComponentWillMount 以及其他通用回调中运行,但我希望每次收到通知时都会调用它,而不管我在哪个页面上。
解决方案
您正在寻找的是主题的概念。您需要在应用程序中收到通知的地方广播事件。您设置的任何对通知感兴趣的屏幕都可以注册以收听这些事件。这是一个在 JS 中实现的基本主题,我在生产中使用它来完全按照您的描述进行操作。
const _handlers = {}
const Subject = {
subscribe (...args) {
const [event, handler] = args
if (!_handlers[event]) _handlers[event] = []
_handlers[event].push(handler)
},
unsubscribe (...args) {
const [event, handler] = args
if (!_handlers[event]) return
_handlers[event] = _handlers[event].filter(func => func !== handler)
},
next (...args) {
const [event, value] = args
if (!_handlers[event]) return
_handlers[event].forEach(handler => {
if (typeof handler === 'function') {
handler(value)
}
})
}
}
Object.freeze(Subject)
module.exports = Subject
您可以像这样在组件中使用它:
notificationHandler = (payload) => {
// Do something with the payload in your screen
}
componentDidMount () {
Subject.subscribe('notification_received', this.notificationHandler)
}
componentWillUnmount () {
Subject.unsubscribe('notification_received', this.notificationHandler)
}
当您收到通知时,您的通知侦听器可以调用Subject.next('notification_received', payload)
推荐阅读
- pandas - 有没有比python中具有不同键的嵌套字典更有效和可读的替代方法?
- c++ - 65536 之后的 C++ 数学怪异
- java - JPA 自定义存储库不是实体:类
- html - P5JS:如何使背景图像重复?
- javascript - 使用 awaitReactions() 函数时如何修复超时错误?
- python - 将值聚合到字符串等列表中,然后转换为真正的列表数据类型
- python - 如何在 Airflow 中更新 AwsBatchOperator 任务代码?
- terraform - Terraform 忽略 AWS metric_query 中的子块更改
- .net - 如何使用 AWS Lamda 和 dotnet Core 5 将 Excel 上传到 Amazon S3?
- unreal-engine4 - 生成蓝图不会生成任何东西(UE4)