NetInfo.addEventListener не работает в реагировать родной - PullRequest
0 голосов
/ 10 января 2019

Я использую компонент NetInfo в реагирующем для определения состояния сети и продолжаю прослушивать сеть с помощью NetInfo.addEventListener () в реагирующем. Но когда я меняю сетевое соединение с Wi-Fi на Интернет или наоборот, состояние не слушает Мой код выглядит следующим образом:

  import React, {Component, PropTypes} from 'react';

   import {
   Platform,
   View,
   Text,
   Image,
    StyleSheet,
   AsyncStorage, 
   BackHandler,
   StatusBar  ,
   NetInfo,
  Alert
 } from 'react-native';
 const iconBasePath = './../../assets/images/'
   import App from './../../App'
  import EventsList from './EventsList'
  import LoginScreen from './LoginScreen'
 import Storage from 'react-native-storage'
 import EventDetails from './EventDetails'
 import DeviceInfo from 'react-native-device-info';
 import RegisterDeviceApiMgr from './../ApiMgrs/RegisterDeviceApiMgr'
   import * as firebase from 'firebase'

 import { GoogleAnalyticsTracker } from 'react-native-google- 
 analytics-bridge'
 import ComponentBase from '../ComponentBase';
import FlashMessage from "react-native-flash-message";
// import  { Firebase } from 'react-native-firebase'
import '@firebase/messaging';
import firebaseNotification from 'react-native-firebase';
import RegisterScreen from './RegisterScreen'
let tracker = new GoogleAnalyticsTracker('*******')

var config = {
  apiKey: "*******",
  authDomain: "*****",
  databaseURL: "****",
  projectId: "*******"
  }
  firebase.initializeApp(config);

 export default  class SplashScreen extends ComponentBase {

  constructor(props){
    super(props);

    this.state = {
        timePassed: false,
        deviceId:"",
        id:"",
        index:2,
    };
}

componentWillUnmount() {
    // this.notificationDisplayedListener();
    // this.notificationListener();
    // this.notificationOpenedListener();
    // this.onTokenRefreshListener();

}
async checkFirebase(){
    console.log("inside checkfirebase 123");
    try{
        const enabled = await firebaseNotification.messaging().hasPermission();
        if (enabled) {
            console.log("inside  enabled");

            // user has permissions
            // this.registerFbCloudMessagingListener()
            this.getToken();

        } else {
            // user doesn't have permission
            console.log("inside else  enabled");

            this.requestFbPermission()
        }

    }
    catch(error){
        console.log("checkfirebase",error.message);
    }

}
async requestFbPermission(){
    try {
        let permission = await firebaseNotification.messaging().requestPermission();
        if (permission) {
            console.log("inside permission  ");

            this.checkFirebase();
        }
        // User has authorised
    } catch (error) {
        console.log("inside error  permission",error.message);

        // User has rejected permissions
    }
}


async getToken(){
    try{
        let token = await firebaseNotification.messaging().getToken();
        console.log("FIREBASE TOKEN", token);
        const tokenSave = await AsyncStorage.setItem('tokenSave', token);

        // const deviceId = DeviceInfo.getUniqueID();
        //              this.setState({
        //                  deviceId:deviceId
        //              })
        //              this.registerDevice(token , deviceId);
    }
    catch(error){
        console.log("while getting token error",error.message);
    }


}

 async componentDidMount() {
       NetInfo.getConnectionInfo().then((connectionInfo) => {
    console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
  });
  function handleFirstConnectivityChange(connectionInfo) {
    console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
    NetInfo.removeEventListener(
      'connectionChange',
      handleFirstConnectivityChange
    );
  }
  NetInfo.addEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );

    firebaseNotification.analytics().setCurrentScreen("SplashScreen");
    const value = await AsyncStorage.getItem('SignInStatus');
    // const userId = await 
    AsyncStorage.setItem("userId",this.state.id);
    // const deviceId = await 
   AsyncStorage.setItem('deviceId',this.state.deviceId);
    console.log("value issssssssssssssssssssssssss",value);
    firebaseNotification.notifications().getInitialNotification()
    .then((notificationOpen) => {
        console.log("received when app closed",notificationOpen);
      if (notificationOpen) {
          console.log("received notifi",notificationOpen);
        // App was opened by a notification
        // Get the action triggered by the notification being opened
         const data = notificationOpen.notification._data;
         console.log("received notifi event id",data.my_key);
         if(value =='true'){
         this.props.navigation.navigate('EventDetails',{eventId:data.my_key, index:this.state.index, lastScreen:'BaseScreen'})
        // Get information about the notification that was opened
         const notification = notificationOpen.notification;  
         console.log("received notification ",notification);
         } 
         else{
            this.props.navigation.navigate('LoginScreen'); 
        //  this.props.navigation.navigate('RegisterScreen'); 
         }
      }
      else{
        this.checkFirebase();
          console.log("time passed set")
          setTimeout( () => {
            this.setTimePassed();    
         }, 5000);

      }
    });
    // this.notification();
    tracker.trackScreenView('SplashScreen')
}

// registerDevice(token , deviceId){
//     let apiMgr = new RegisterDeviceApiMgr();
//     apiMgr.putDeviceData(token , deviceId)
//     .then((Data) => {
//         var deviceresponse = JSON.parse(Data._bodyInit)
//          console.log("SUcessssssssss Registering Device "+JSON.stringify(deviceresponse.user._id))
//          this.setState({
//              id:deviceresponse.user._id
//          })
//          this.setId(deviceresponse.user._id);
//         // this.props.navigation.navigate('EventDetails',{eventCode:this.state.EventCode ,eventId:this.state.eventId, index:this.state.indx,lastScreen:'UserData'})
//      })
//      .catch( (error) => {
//          console.log(error);
// if(error == 'TypeError: Network request failed'){
//   Alert.alert('Something went wrong', 'Kindly check if the device is connected to stable cellular data plan or WiFi.'); 
//  }

//      });
// }
// setId=async(deviceresponse)=>{
//     try{
//         console.log("user id",deviceresponse);
//         const userId = await AsyncStorage.setItem("userId",deviceresponse);
//         console.log("setting id is",this.state.id);

//     }
//     catch(error){
//         console.error(error.message);
//     }
// }

setTimePassed = async () =>{
    try {
        // console.log("userid and device id",this.state.id+" "+this.state.deviceId);
       const value = await AsyncStorage.getItem('SignInStatus');
    //    const userId = await AsyncStorage.setItem("userId",this.state.id);
    //    const deviceId = await AsyncStorage.setItem('deviceId',this.state.deviceId);
       console.log("value is",value);
       if (value == "true"){
          // alert(JSON.stringify(this.state.id))
          console.log("value present",value);
          this.props.navigation.navigate('EventsList')  
        }
        else {
           // alert(JSON.stringify(this.state.id))
           this.props.navigation.navigate('LoginScreen'); 
         //  this.props.navigation.navigate('RegisterScreen');
       }
        //    this.props.navigation.navigate('LoginScreen'); 

      } 

      catch (error) {
        console.log("value not present",error.message);

      }

 }
  render() {
       if(!this.state.timePassed){
        return(
            <View style = { styles.MainContainer }>
            <StatusBar
                   backgroundColor="#000080"
                   barStyle="light-content"/>

                <View style={styles.SplashScreen_RootView}>

                    <View style={styles.SplashScreen_ChildView}>

                        {/* Put all your components Image and Text here inside Child view which you want to show in Splash Screen. */}
                        <Image  source={require('./../../assets/NewWrapo.jpg')}
                        style={{width:'100%', height: '100%', resizeMode: 'contain'}} />

                    </View>

                </View>

            </View>
        )
    }

   }
 }


const styles = StyleSheet.create(
   {
    MainContainer:
    {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
  //          paddingTop: ( Platform.OS === 'ios' ) ? 20 : 0
    },

    SplashScreen_RootView:
    {
                justifyContent: 'center',
                flex:1,
  //            margin: 10,
                position: 'absolute',
                width: '100%',
                height: '100%',

      },

       SplashScreen_ChildView:
      {
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#1F0242',
            flex:1,
  //            margin: 20,
    },

    TouchableOpacity_Style:{

        width:25, 
        height: 25, 
        top:9, 
        right:9, 
        position: 'absolute'

    }
});

Я добавляю приведенный выше код в метод componentDidMount (). Здесь я вижу только выходные данные только для NetInfo.getConnectionInfo (), но не для NetInfo.addEventListener (). Пожалуйста, помогите мне.

Ответы [ 2 ]

0 голосов
/ 10 января 2019

Сначала: Попробуйте добавить EventListener перед монтированием компонента ( componentWillMount ) и удалить его перед размонтированием ( componentWillUnmount ).

Еще один момент: зачем вашему компоненту обновлять и печатать файл console.log, если состояние не изменилось? Ваш метод handleConnectionChange ничего не делает. Сначала измените это и загрузите значение ( isConnected ) в ваше состояние.

0 голосов
/ 10 января 2019

Убедитесь, что у вас есть правильные разрешения ..

Android:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...