如何在React Native状态下保存一个信号玩家ID

问题描述 投票:0回答:3

我是原生反应新手,我使用一个信号进行通知。我从

OneSignal.configure();
得到了一个信号用户玩家 ID,并通过遵循我已经完成的代码,但该玩家 ID 只能在控制台上看到。我正在使用
setState
保存状态,但显示错误
setState is not a function
。我怎样才能获得该玩家ID以将其保存在状态中。

代码:

componentWillMount() {
          OneSignal.init("d447e6e2-0c8e-4781-8292-6e77d2e86691");

          OneSignal.configure();
          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);
      }

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

      onIds(device) {
        console.log('Device info: ', device);
      console.log('player id: ', device.userId);
       this.setState({
            pid: device.userId,
          })
       console.log(this.state.pid);
      }
reactjs push-notification react-native onesignal
3个回答
5
投票

事件侦听器函数不知道您的

this
,因此您必须使用
bind
将您的
this
放入其中。

componentWillMount() {
    OneSignal.init('ONESIGNAL-APP-ID');

    OneSignal.addEventListener('received', this.onReceived.bind(this));
    OneSignal.addEventListener('opened', this.onOpened.bind(this));
    OneSignal.addEventListener('ids', this.onIds.bind(this));
    OneSignal.configure();
}

更新

您还可以声明为箭头函数以避免 .bind(this):

componentWillMount() {
    OneSignal.init('ONESIGNAL-APP-ID');

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

onReceived = () => {}
onOpened = () => {}
onIds = () => {}

4
投票

你也可以通过这种方式获取玩家ID:

const data = await OneSignal.getDeviceState();

const player_id=data.userId;

参考:- https://stackoverflow.com/a/72224052/5783617


0
投票

如果您使用新的 Onesignal 版本,请按照此代码操作

OneSignal.User.pushSubscription.optIn()
        OneSignal.User.addTag("user_type", "customer");
        OneSignal.User.pushSubscription.addEventListener('change', (subscription) => {
            console.log(subscription?.current?.id)
        });

之后清除您的应用程序缓存或卸载您的应用程序,然后运行

© www.soinside.com 2019 - 2024. All rights reserved.