以优雅的方式处理通知响应-React Native

时间:2019-03-27 12:59:45

标签: firebase react-native events push-notification firebase-cloud-messaging

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

我参考了下一页以了解如何收到回复-
https://rnfirebase.io/docs/v5.x.x/notifications/receiving-notifications

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

当前它仅在构造函数和ComponentWillMount及其他通用回调中运行,但是无论我在哪个页面上,我希望每次收到通知时都调用该函数。

1 个答案:

答案 0 :(得分:0)

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