简体   繁体   中英

Possible unhandled promise Rejection (id:0) React Native

Having error, dunno what's wrong in here. Any idea? I need to get longitude and latitude. kindly tell me if there are any other good approach with Expo created react native project. thanks!

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { Location, Permissions } from 'expo';
import React from 'react';

export default class App extends React.Component{

  state = {
    location: {},
    erroMessage: '',
  }

  componentWillMount(){
    this._getLocation();
  }

  _getLocation = async () => {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if(status !== 'granted'){
      console.log('PERMISSION NOT GRANTED!');

      this.setState({
        erroMessage: 'PERMISSIN NOT GRANTED'
      })
    }

    const location = await Location.getCurrentPositionAsync();

    this.setState({
      location,
    });

  };

  render () {
    return (
      <View style={styles.container}>
        <Text>{JSON.stringify(this.state.location)}</Text>
        <StatusBar style="auto" />
      </View>
    );
  }
}

You don't have any error handling for either Promises that come from Permissions.askAsync and Location.getCurrentPositionAsync . Wrap the awaited functions in a try / catch block and handle any errors from the error block.

_getLocation = async () => {
  try {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if(status !== 'granted'){
      console.log('PERMISSION NOT GRANTED!');

      this.setState({
        erroMessage: 'PERMISSIN NOT GRANTED'
      });
    }

    const location = await Location.getCurrentPositionAsync();

    this.setState({
      location,
    });
  } catch (error) {
    // Handle any errors here.
  }
};

You need to add else condition as well. If permission is not granted stop execution or ask again for permissions.

_getLocation = async () => {
try {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status !== 'granted') {
        console.log('PERMISSION NOT GRANTED!');

        this.setState({
            erroMessage: 'PERMISSIN NOT GRANTED',
        });
    } else {
        const location = await Location.getCurrentPositionAsync();

        this.setState({
            location,
        });
    }
} catch (error) {
    // Handle any errors here.
}

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM