首页 > 解决方案 > 无法获取用户 ID(PlayerID)。未定义(ReactNative、OneSignal)

问题描述

通过我的应用程序,我将通过 OneSignal 发送通知。但我无法从 OneSignal 获取用户 ID。我从 GET 请求中读取了这个用户 ID,并将其保存在数据库中。在我通过 PHP 发送通知之后。

如果我总是不确定,我怎么能得到这个用户 ID?

export default class App extends Component {

  constructor(props) {
    super(props);
    this.WEBVIEW_REF = React.createRef();
  }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    OneSignal.setLogLevel(6, 0);
    OneSignal.setAppId("fdb89158-4072-4964-b490-6ba70fb6b5fd");

    OneSignal.promptForPushNotificationsWithUserResponse(response => {
    });

    OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
      let notification = notificationReceivedEvent.getNotification();
      console.log("notification: ", notification);
      const data = notification.additionalData
      console.log("additionalData: ", notification.additionalData);
      notificationReceivedEvent.complete(notification);
    });

    OneSignal.setNotificationOpenedHandler(notification => {
    });

    OneSignal.addPermissionObserver(event => {
      console.log("OneSignal: permission changed:", event);
  });

  OneSignal.addSubscriptionObserver(event => {
    console.log("OneSignal: subscription changed to userId:", event.to.userId);
  });
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }

  handleBackButton = ()=>{
    this.WEBVIEW_REF.current.goBack();
    return true;
  }

  onNavigationStateChange(navState) {
    this.setState({
      canGoBack: navState.canGoBack
    });
  }
  render() {
    const deviceState = OneSignal.getDeviceState();
    return (
        <WebView
        source={{ uri: 'https://www.google.com/search?q='+ deviceState.userId}}
        style={{ marginTop: 35 }}
        ref={this.WEBVIEW_REF}
        onNavigationStateChange={this.onNavigationStateChange.bind(this)}
      />
    );
}
}

标签: react-nativeonesignal

解决方案


getDeviceState返回一个异步的,因此请确保您正在等待它。


推荐阅读