首页 > 解决方案 > React Native Expo 推送通知重定向无法正常工作

问题描述

我能够在我的 react native 应用程序中成功接收推送通知,但我无法根据它们进行重定向。发生的情况是,在 android 上,当我触摸通知时,应用程序完全重新加载并且通知数据丢失。我该如何处理?

这是我的代码

import React from 'react';
import { AppState, View, StatusBar } from 'react-native';
import { ScreenHost } from './src/app/screen-host';
import { AppHost } from './src/debug/app-host';
import { settings } from './src/constants/settings';
import { services } from './src/services/services';
import Expo from 'expo';

async function getToken() {
  // Remote notifications do not work in simulators, only on device
  if (!Expo.Constants.isDevice) {
    return;
  }
  let { status } = await Expo.Permissions.askAsync(
    Expo.Permissions.NOTIFICATIONS,
  );
  if (status !== 'granted') {
    return;
  }
  let value = await Expo.Notifications.getExpoPushTokenAsync();
  console.log('Our token', value);
}

export default class App extends React.Component {

  state = {
    appState: AppState.currentState,
    conv_id: ''
  }

  componentDidMount() {
    getToken();
    AppState.addEventListener('change', this._handleAppStateChange);
    //Expo.Notifications.setBadgeNumberAsync(0);
  }  

  componentWillUnmount() {
    this.listener && this.listener.remove();
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if(this.state.conv_id == ''){
      this.listener = Expo.Notifications.addListener(this.handleNotification);
    }
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!');
      if(this.state.conv_id != ''){
        services.store.gotoConversation(this.state.conv_id);
      }
    }
    Expo.Notifications.setBadgeNumberAsync(0);
    this.setState({appState: nextAppState});
  }

  handleNotification = ({ origin, data }) => {
    console.log(origin);
    this.state.conv_id = data.conv_id;
  };

  render() {
    if (settings.useDebugLayout) {
      return (
        <AppHost>
          <AppMain />
        </AppHost>
      );
    } else {
      return (
        <AppMain />
      );
    }
  }
}

class AppMain extends React.Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <StatusBar barStyle="light-content" />
        <ScreenHost data={services.store._showNav}/>
      </View>
    );
  }
}

我想打电话给我services.store.gotoConversation(this.state.conv_id);,但屏幕加载了启动画面并且通知数据丢失了。

我经历了

https://docs.expo.io/versions/latest/guides/push-notifications

但我似乎无法弄清楚主要问题是什么。请帮我。我将奖励50 Bounty那些曾经帮助我解决我的问题的人。谢谢你。

标签: javascriptreact-nativepush-notificationreact-navigationexpo

解决方案


推荐阅读