在我的react native应用程序中,在主屏幕中有一个按钮可以打开一个指南针,以显示特定位置的方向。为此,我需要将用户的坐标传递到指南针屏幕以进行计算,并在导航器中传递值。
我在主屏幕的componentDidMount()方法上加载坐标,我的问题是获取用户坐标有时会花费一些时间(取决于用户的gps信号强度和他/她的设备),所以我使用了如果用户在加载坐标之前按了指南针按钮,则条件渲染将显示“加载”组件。但是问题在于,我不知道如何在装载机之后将他/她送到指南针屏幕,因为现在装载机之后,他/她停留在主屏幕中,必须再次按下按钮才能进入指南针。>
state = {
currentLongitude: "unknown",
currentLatitude: "unknown",
locationLoading: false,
};
getCards = () => [...
{id: "3",
card: this.languageCard("Compass"),
onPress: () => {
this.state.currentLatitude != "unknown"
? this.props.navigation.navigate("Compass", {
latitude: this.state.currentLatitude,
longitude: this.state.currentLongitude,
})
: this.setState({ locationLoading: true });
},
}...]
componentDidMount() {
this.requestLocation();
}
requestLocation() {
var that = this;
if (Platform.OS === "ios") {
this.callLocation(that);
} else {
async function requestLocationPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Access Required",
message: "This App needs to Access your location",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
that.callLocation(that);
} else {
alert("Permission Denied");
}
} catch (err) {
alert("err", err);
console.warn(err);
}
}
requestLocationPermission();
}
}
callLocation(that) {
Geolocation.getCurrentPosition(
(position) => {
const currentLongitude = JSON.stringify(position.coords.longitude);
const currentLatitude = JSON.stringify(position.coords.latitude);
that.setState({ currentLongitude: currentLongitude });
that.setState({ currentLatitude: currentLatitude });
this.setState({ locationLoading: false });
},
(error) => alert(error.message),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
);
}
render() {
return this.state.locationLoading ? (
<Loader />
) : (
<SafeAreaView>
....
</SafeAreaView>