调用utils.js文件中的异步函数(React-Native)?



我正在为我的投资组合构建一个react-native天气应用程序。

我希望能够在我的utils.js文件中调用辅助函数。该函数是一个异步箭头函数,负责检索经纬度坐标。

函数返回一个数组中的坐标,我使用析构来设置组件中的状态。

然而,我在控制台中得到一个警告,声明如下:

WARN Possible Unhandled Promise Rejection (id: 1): TypeError:Undefined不是一个对象(求值)_ $ $ _REQUIRE (_dependencyMap [11],". ./跑龙套/utils") .globalFunctions.getLocation")

我可能做错了什么?如有任何帮助,不胜感激。

Utils.js

import {PermissionsAndroid} from 'react-native';
import Geolocation from 'react-native-geolocation-service';
const globalFunctions = {
getLocation: async () => {
const coordinates = [];
const hasLocationPermission = await 
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (hasLocationPermission == PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
position => {
console.log('Geolocation Granted');
console.log(position);
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
coordinates.push(latitude);
coordinates.push(longitude);
return coordinates;
},
error => {
console.log(error.code, error.message);
},
{enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
);
} else {
console.log('User denied Geolocation');
}

},

};WeatherContainer.js

import React, {Component} from 'react';
import {Text, Image, StyleSheet, View, StatusBar} from 'react-native';
import {globalFunctions} from '../Utils/utils';
class WeatherContainer extends Component {
constructor() {
super();
this.state = {
lat: null,
lon: null,
};
}
componentDidMount = () => {
this.getLocationData();
};
getLocationData = async () => {
const [latitude, longitude] = await globalFunctions.getLocation();
this.setState({
lat: latitude,
lon: longitude,
});
};
render() {
return (
<View style={styles.container}>
<View style={styles.innerContainer}>
<Text style={styles.location}>{this.state.lat}</Text>
<Text>{this.state.lon}</Text>
</View>
</View>
);
}
}

您需要从Utils.js导出globalFunctions函数

const export globalFunctions

最新更新