首页 > 解决方案 > 优雅地处理通知响应 - React Native

问题描述

我试图在 React Native(0.55.4)中设置通知,我使用反应导航来渲染我的屏幕。一切都设置好了,我正在接收通知并且能够读取有效负载

我参考了以下页面以了解如何收到响应 -
https://rnfirebase.io/docs/v5.xx/notifications/receiving-notifications

我想知道如何合并它,以便在收到通知时在我的反应导航的任何页面中调用一个事件,或者在后台调用它并根据有效负载进行处理。

目前它仅在构造函数和 ComponentWillMount 以及其他通用回调中运行,但我希望每次收到通知时都会调用它,而不管我在哪个页面上。

标签: firebasereact-nativeeventspush-notificationfirebase-cloud-messaging

解决方案


您正在寻找的是主题的概念。您需要在应用程序中收到通知的地方广播事件。您设置的任何对通知感兴趣的屏幕都可以注册以收听这些事件。这是一个在 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)


推荐阅读