React Native:Null不是对象-推送通知(OneSignal)

时间:2019-01-21 20:11:10

标签: android ios react-native state onesignal

此刻,我的推送通知遇到问题..我正在尝试在我的存储库中初始化OneSignal,并且已遵循OneSignal安装指南并已对其进行了仔细检查。一切设置正确!

但是,我有两个问题,在iOS和Android上是不同的。有三种接收推送通知的方法:

  • 情况1:应用已打开
  • 情况2:该应用已打开,已关闭(未终止)并仍在后台运行
  • 情况3:该应用未打开且未在后台运行(已被杀死/从屏幕上清除)

iOS: 在我的iPhone上,案例1和案例2可以正常工作,没有任何问题。但是,在第3种情况下,我的应用程序正在显示此屏幕(下面的图像)。

Android: 在Android手机上,情况1和3可以正常工作,但在情况2中,该应用程序未显示我的弹出对话框。但是也没有崩溃和运行!

因此,我认为,就像iOS屏幕告诉我的那样,我的状态存在某个问题,因为它是null。但是,在我眼里还是令人困惑,因为这种情况确实适用于Android。

但是,我正在使用OneSignal文档中提供的功能和EventHandler。另外,我正在使用名为react-native-popup-dialog的库来在发送推送通知时显示弹出窗口。仅当我通过推送通知发送某些键/值对时,此弹出窗口才可见。这些键是:

  1. showPopuptrue-为true时显示弹出窗口。如果未设置或不等于true,则不会显示!
  2. openLinkmydomain.de-添加带有链接到弹出窗口的按钮
  3. buttonTextOpen in Browser-将按钮文本设置为链接
  

请注意,只有在设置了键openLinkbuttonText的情况下,才会将额外的URL按钮添加到弹出窗口中。它们中没有一个或仅设置了一个键,它没有显示此按钮。

到目前为止,一切都很好。所以,现在这是我的源代码,希望大家能帮帮我..尝试调试三天以来……

  

请注意,扩展了(SuperScreen)类的几个(不同)屏幕调用了getPopup()方法。

import Dialog, { SlideAnimation, DialogTitle, DialogContent, DialogButton } from "react-native-popup-dialog";
import firebase from "react-native-firebase";
import OneSignal from "react-native-onesignal"

export default class SuperScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pushNotification: null,
      visible: false
    };

    OneSignal.setLogLevel(6, 0);
    OneSignal.init("00000000000000000000000000000000000", {
      kOSSettingsKeyAutoPrompt: true
    });

    OneSignal.inFocusDisplaying(0);
    OneSignal.enableVibrate(true);
    OneSignal.enableSound(true);

    OneSignal.addEventListener("received", this.onReceived);
    OneSignal.addEventListener("opened", this.onOpened);
    OneSignal.addEventListener("ids", this.onIds);
}

  componentWillUnmount() {
    OneSignal.removeEventListener("received", this.onReceived);
    OneSignal.removeEventListener("opened", this.onOpened);
    OneSignal.removeEventListener("ids", this.onIds);
  }

  onReceived = notification => {
    console.log("Notification received: ", notification);

    this.setState({
      pushNotification: notification,
      visible: true
    });

    if (this.state.pushNotification.payload.notificationID != null) {
      firebase.analytics().logEvent("Popup_Link_Button", {
        notificationID: this.state.pushNotification.payload.notificationID,
        clicked: true
      });
    }
  };

  onOpened = openResult => {
    console.log("Message: ", openResult.notification.payload.body);
    console.log("Data: ", openResult.notification.payload.additionalData);
    console.log("isActive: ", openResult.notification.isAppInFocus);
    console.log("openResult: ", openResult);

    this.setState({
      pushNotification: openResult.notification,
      visible: true
    });

    if (this.state.pushNotification.payload.notificationID != null) {
      firebase.analytics().logEvent("Popup_Link_Button", {
        notificationID: this.state.pushNotification.payload.notificationID,
        clicked: true
      });
    }
  };

  onIds = device => {
    console.log("Device info: ", device);
  };

  getPopup() {
    if (
      this.state.pushNotification != null &&
      this.state.pushNotification.payload.additionalData != null &&
      this.state.pushNotification.payload.additionalData.showPopup != null &&
      this.state.pushNotification.payload.additionalData.showPopup == "true"
    ) {
      var actionButtons = null;

      if (
        this.state.pushNotification.payload.additionalData.openLink != null &&
        this.state.pushNotification.payload.additionalData.buttonText != null
      ) {
        actionButtons = [
          <DialogButton
            text="Ok"
            key={0}
            onPress={() => {
              this.setState({ visible: false });
              firebase.analytics().logEvent("Popup_Link_Button", {
                notificationID: this.state.pushNotification.payload
                  .notificationID,
                opened: false
              });
            }}
          />
        ];

        actionButtons.push(
          <DialogButton
            text={this.state.pushNotification.payload.additionalData.buttonText}
            key={1}
            onPress={() => {
              this.openLink(
                this.state.pushNotification.payload.additionalData.openLink
              );
              this.setState({ visible: false });
              firebase.analytics().logEvent("Popup_Link_Button", {
                notificationID: this.state.pushNotification.payload
                  .notificationID,
                link: this.state.pushNotification.payload.additionalData
                  .openLink,
                opened: true
              });
            }}
          />
        );
      } else {
        actionButtons = [
          <DialogButton
            text="Ok"
            key={0}
            onPress={() => {
              this.setState({ visible: false, pushNotification: null });
              firebase.analytics().logEvent("Popup_Link_Button", {
                popupID: this.state.pushNotification.payload.notificationID,
                opened: false
              });
            }}
          />
        ];
      }

      return (
        <Dialog
          visible={this.state.visible == null ? false : this.state.visible}
          dialogTitle={
            <DialogTitle
              title={
                this.state.pushNotification == null
                  ? ""
                  : this.state.pushNotification.payload.title
              }
            />
          }
          dialogAnimation={
            new SlideAnimation({
              slideFrom: "bottom"
            })
          }
          dialogStyle={{ marginLeft: 20, marginRight: 20 }}
          actions={actionButtons}
        >
          <DialogContent>
            <Text />
            <Text>
              {this.state.pushNotification == null
                ? ""
                : this.state.pushNotification.payload.body}
            </Text>
          </DialogContent>
        </Dialog>
      );
    }
  }

我的iPhone图像:

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

问题是您使用的状态值尚未设置。设置状态是异步操作,因此不能保证在您调用它时就将其设置。

您应该直接使用通知对象,而不是设置为要声明的对象。

您可以在此处了解有关设置状态的更多信息

https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0

这是我的意思的一个例子。

using System.Threading;

Timer delayedActionTimer;

public MyClass()
{
    // Setup our timer
    delayedActionTimer = new Timer(saveOrWhatever, // The method to call when triggered
                                   null, // State object (Not required)
                                   Timeout.Infinite, // Start disabled
                                   Timeout.Infinite); // Don't repeat the trigger
}

// A change was made that we want to save but not until a
// reasonable amount of time between changes has gone by
// so that we're not saving on every keystroke/trigger event.
public void TextChanged()
{
    delayedActionTimer.Change(3000, // Trigger this timers function in 3 seconds,
                                    // overwriting any existing countdown
                              Timeout.Infinite); // Don't repeat this trigger; Only fire once
}

// Timer requires the method take an Object which we've set to null since we don't
// need it for this example
private void saveOrWhatever(Object obj) 
{
    /*Do the thing*/
}

您还需要更新onOpened函数