繁体   English   中英

可能未处理的 promise Rejection (id:0) React Native

[英]Possible unhandled promise Rejection (id:0) React Native

有错误,不知道这里有什么问题。 任何想法? 我需要得到经度和纬度。 请告诉我 Expo 创建的 react native 项目是否还有其他好的方法。 谢谢!

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

对于来自Permissions.askAsyncLocation.getCurrentPositionAsync的 Promise,您没有任何错误处理。 将等待的函数包装在try / catch块中并处理来自error块的任何错误。

_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.
  }
};

您还需要添加else条件。 如果未授予权限,请停止执行或再次请求权限。

_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.
}

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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