使用 Headless JS 任务来处理推送通知的示例 React Native 应用程序

Zal*_*oza 5 push-notification reactjs react-native onesignal

我在我的网络应用程序中使用 onesignal 来提供推送通知。

当我开始编写 React-native 应用程序时,我想知道是否有人可以提供一个有用的示例来展示如何使用 React-native 处理推送通知。

目前我所做的是在我的根组件构造函数中注册推送通知。但由于很少有关于具体何时运行的文档,我不确定是否应该将其移至 index.android.js 文件旁边进行AppRegistry.registerComponent调用?或者此时是否不能保证js环境已完全加载?

当前代码”

// index.android.js,index.ios.js
import React from 'react';
import {AppRegistry,Text,View} from 'react-native';

import OneSignal from 'react-native-onesignal';

class App extends Component {
  constructor(props) {
    // config oneSignal push and do startup tasks..
    this.$device = {};
    this.$push = []; // array to hold pending notifications.. just to 
                     // prevent losing them case app ui was not fully loaded when config is called
    OneSignal.configure({
        onIdsAvailable: (device) => {
          console.log('UserId = ', device.userId);
          console.log('PushToken = ', device.pushToken);
          this.$device = device; //save em..
        },
        onNotificationOpened: (message, data, isActive) => {
          const notification = {
            message,
            data,
            isActive,
          };
          this.$push.pending.push(notification);
        },
      });
      OneSignal.clearOneSignalNotifications();
      OneSignal.enableVibrate(true);
      OneSignal.enableSound(true);
      OneSignal.requestPermissions({
        alert: true,
        badge: true,
        sound: true,
      });
      OneSignal.setSubscription(true);
  }
  render(){return <View><Text>My App will run here..</Text></View>;}
}
AppRegistry.registerComponent('AppName', () => ()=><App />);
Run Code Online (Sandbox Code Playgroud)

可以将构造函数逻辑从我的根标签移到index.js 文件的主体吗?或者更好地保持这种方式?

当收到 oneSignal 通知时,AppRegistry 会被调用吗?

如果我要将其转移到无头任务,它会是什么样子?