如何从推送通知打开路由

如何从推送通知打开路由

本文介绍了React Native - 如何从推送通知打开路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-navigationreact-native-push-notification.如何在 onNotification 回调中打开某个 StackNavigator's 屏幕?应该在以下情况下工作:

I'm using react-navigation and react-native-push-notification. How can I open a certain StackNavigator's screen in onNotification callback? Should work when:

  • 应用已关闭
  • 应用在前台
  • 应用在后台

我现在只需要它在 Android 上运行.

I only need it working in Android for now.

我尝试将回调函数传递给组件中的通知:

I've tried to pass a callback function to notification in my component:

_handleClick() {
  PushNotification.localNotification({
    foreground: false
    userInteraction: false
    message: 'My Notification Message'
    onOpen: () => { this.props.navigation.navigate("OtherScreen") },
  })
}

并在 PushNotification 配置中触发 onOpen:

And to fire onOpen in PushNotification config:

onNotification: function(notification) {
   notification.onOpen()
}

但似乎函数无法传递给通知,除非值是一个字符串,否则它会被忽略,导致 onOpen 未定义.

But it seems that functions can't be passed to notification, unless a value is a string it's ignored, causing onOpen to be undefined.

推荐答案

好吧,看来我得发布我自己的解决方案了 :)

Okay, it seems like I gotta post my own solution :)

// src/services/push-notification.js
const PushNotification = require('react-native-push-notification')

export function setupPushNotification(handleNotification) {
  PushNotification.configure({

      onNotification: function(notification) {
        handleNotification(notification)
      },

      popInitialNotification: true,
      requestPermissions: true,
  })

  return PushNotification
}


// Some notification-scheduling component
import {setupPushNotification} from "src/services/push-notification"

class SomeComponent extends PureComponent {

  componentDidMount() {
    this.pushNotification = setupPushNotification(this._handleNotificationOpen)
  }

  _handleNotificationOpen = () => {
    const {navigate} = this.props.navigation
    navigate("SomeOtherScreen")
  }

  _handlePress = () => {
    this.pushNotification.localNotificationSchedule({
      message: 'Some message',
      date: new Date(Date.now() + (10 * 1000)), // to schedule it in 10 secs in my case
    })

  }

  render() {
    // use _handlePress function somewhere to schedule notification
  }

}

这篇关于React Native - 如何从推送通知打开路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 15:41