[英]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.askAsync
和Location.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.