React Native:一个信号推送通知设置状态

时间:2019-01-12 11:20:58

标签: reactjs react-native onesignal setstate

我在我的react本机应用程序上安装了OneSignal package,并希望将通知插入到我的状态,以便可以在类中访问该通知。

所以,到目前为止,我一直尝试这样做:

import OneSignal from "react-native-onesignal";

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

    OneSignal.init("<mykey>", {kOSSettingsKeyAutoPrompt: true});
    OneSignal.inFocusDisplaying(0);

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

componentWillUnmount() {
    OneSignal.removeEventListener("opened", this.onOpened);
}

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});
}

但是我总是得到this.setState(...)不是一个函数。所以我在这行添加了修改:

this.setState({ pushNotification: openResult}).bind(this);

但是,我仍然得到相同的结果。我只想更新状态。你们能解释一下我为什么收到此错误消息以及如何解决该错误消息吗?

致以问候,谢谢!

1 个答案:

答案 0 :(得分:3)

发生该错误是因为onOpened未绑定到类组件,因此thisonOpened的值不是您所期望的(只是null

要修复它,您可以使用类属性+箭头功能

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});
}

或者您可以使用.bind(this)

将其绑定到构造函数中
 constructor(props) {
    super(props);
    this.state = {
      showPopup: false,
      pushNotification: null
    };

    this.onOpened = this.onOpened.bind(this); // <--- here

    OneSignal.init("<mykey>", {kOSSettingsKeyAutoPrompt: true});
    OneSignal.inFocusDisplaying(0);

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