【问题标题】:React Native: One Signal push notification set stateReact Native:One Signal 推送通知设置状态
【发布时间】:2019-01-12 11:20:57
【问题描述】:

我已经在我的 react native 应用程序上安装了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);

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

诚挚的问候和感谢!

【问题讨论】:

    标签: reactjs react-native onesignal setstate


    【解决方案1】:

    发生该错误是因为onOpened 未绑定到类组件,因此onOpened 中的this 的值不是您所期望的(它只是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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      相关资源
      最近更新 更多