获取位置时React原生Map应用程序崩溃

zi8p0yeb  于 2023-01-21  发布在  React
关注(0)|答案(1)|浏览(138)

我的项目显示一个react原生Map并询问用户位置。在开发过程中,应用程序运行nickel没有错误或bug或减速,而当我构建应用程序并在应用程序崩溃时安装它时。
演示1:DEMO gif app in developpement npx expo start: works fine演示2:DEMO gif app builded installed with apk: crash
我使用:
"天然React":"0.70.5","世博会":"~47.0.12 ""暴露位置":"~15.0.1 ","@React-原生-社区/地理位置":"^3.0.4","React-本地-Map":"^1.3.2",
包含我的Map的文件:

import React, { useEffect, useRef, useState } from "react";
import {
 ...
} from "react-native";
import { StatusBar } from "expo-status-bar";
import * as Location from "expo-location";
import MapView, { Marker } from "react-native-maps";
import { Alert } from "react-native";

const Planisphere = () => {
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [mapRef, setMapRef] = useState(null);
  const [locationAccepted, setLocationAccepted] = useState(false);

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== "granted") {
        setErrorMsg("Permission to access location was denied");
        Alert.alert(
          "Location Permission Denied",
          "Please go to settings and enable location permission for this app to continue.",
          [
            {
              text: "Go to Settings",
              onPress: () => Linking.openSettings(),
            },
          ]
        );
        return;
      }

      let subscription = await Location.watchPositionAsync(
        { accuracy: Location.Accuracy.BestForNavigation },
        (location) => {
          setLocation(location);
          setLocationAccepted(true);
        }
      );

      return () => subscription.remove();
    })();
  }, []);

  const handleFindMyLocation = () => {
   ...
  };

  const handleUnzoom = () => {
   ...
  };

  let text = "Waiting..";
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);
  }

  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      {location && (
        <MapView
          ref={(ref) => setMapRef(ref)}
          style={styles.map}
          minZoomLevel={8}
          maxZoomLevel={18}
          initialRegion={{
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
        >
          <Marker
            coordinate={{
              latitude: location.coords.latitude,
              longitude: location.coords.longitude,
            }}
            title={"Your location"}
          />
        </MapView>
      )}
      <Text style={styles.paragraph}>{text}</Text>
      {locationAccepted && (
        <View>
          <Button title="Find my location" onPress={handleFindMyLocation} />
          <Button title="Unzoom" onPress={handleUnzoom} />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
 ...
});

export default Planisphere;

我的文件询问位置,当其授权,Map出现.

bxpogfeg

bxpogfeg1#

我认为您需要使用useMemo重新构建您的text

...
const text = useMemo(() => {
  if (errorMsg) {
    return errorMsg;
  } else if (location) {
    return JSON.stringify(location);
  }
  return 'Waiting..'
}, [errorMsg, location])
...

在您的实现中,useEffect的第二个问题是您没有返回close回调return () => subscription.remove();,因为您的异步函数的结果将是Promise
试着把你的功能分成两部分。第一部分请求权限。第二部分是对位置的订阅。

const [subscription, setSubscription] = useState(null)
 useEffect(() => {
   const fetchLocation = async()=> {
     const watcher = await Location.watchPositionAsync(
        { accuracy: Location.Accuracy.BestForNavigation },
        (location) => {
          setLocation(location);
          setLocationAccepted(true);
        }
     );
     setSubscription(watcher)
   }
   if (permissions === 'granted') {
     fetchLocation()
   }
  
   return () => {
     if (subscription) { subscription.remove() }
   }
 }, [permissions]);

相关问题