有关React Native的若干有趣问题

huangapple go评论73阅读模式
英文:

Several Interesting Problem on React Native

问题

以下是您要翻译的内容:

"I want to share on of my react native project. Here I am getting some issues. I have tried to solve that many time, but failed. Can anyone fix that?

I have checked all the questions asked on stack overflow. I can assure that this a really new problem.

Errors: 1. In Location.Address it is showing that address module is not loaded.

  1. Location.requestPermissionsAsync() not working. Showing a cross over the code.

  2. In let {status} it is showing an error.

Please Note I have written this code in a .tsx file."

import React, { useState, useReducer, useEffect } from "react";
import { View, Text, StyleSheet, Image, Dimensions, TouchableOpacity } from "react-native";

import * as Location from "expo-location";

const screenWidth = Dimensions.get("screen").width;

export const LandingScreen = () => {
  const [errorMsg, setErrorMsg] = useState("");
  const [address, setAddress] = useState<Location.Address>();
  const [displayAddress, setDisplayAddress] = useState("Waiting for current location");

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestPermissionsAsync();

      if (status !== "granted") {
        setErrorMsg("permissions not granted, Allow the app to use location service");
      }

      let location: any = await Location.getCurrentPositionAsync();

      const { coords } = location;

      if (coords) {
        const { latitude, longitude } = coords;
        let addressResponse: any = await Location.reverseGeocodeAsync({
          latitude,
          longitude,
        });

        for (let item of addressResponse) {
          setAddress(item);
          let currentAddress = `${item.name}, ${item.street}, ${item.postalCode}, ${item.city}`;
          setDisplayAddress(currentAddress);
        }
      }
    });
  }, []);

  return (
    <View style={styles.container}>
      <View style={styles.navigation} />
      <View style={styles.body}>
        <Image source={require("../images/delivery.png")} style={styles.deliveryIcon} />
        <View style={styles.addressContainer}>
          <Text style={styles.addressTitle}>Your deliver address</Text>
        </View>
        <Text style={styles.addressText}>{displayAddress}</Text>
      </View>
      <View style={styles.footer} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgba(242, 242, 242, 1)',
  },
  navigation: {
    flex: 2,
  },
  body: {
    flex: 9,
    justifyContent: "center",
    alignItems: "center",
  },
  footer: {
    flex: 1,
  },
  deliveryIcon: {
    width: 120,
    height: 120,
  },
  addressContainer: {
    width: screenWidth - 100,
    borderBottomColor: "red",
    borderBottomWidth: 0.5,
    padding: 5,
    marginBottom: 10,
    alignItems: "center",
  },
  addressTitle: {
    fontSize: 24,
    fontWeight: "700",
    color: "#7D7D7D",
  },
  addressText: {
    fontSize: 20,
    fontWeight: "200",
    color: "#4F4F4F",
  },
});
英文:

I want to share on of my react native project. Here I am getting some issues. I have tried to solve that many time, but failed. Can anyone fix that?

I have checked all the questions asked on stack overflow. I can assure that this a really new problem.

Errors: 1. In Location.Address it is showing that address module is not loaded.

2.Location.requestPermissionsAsync() not working. Showing a cross over the code.

  1. In let {status} it is showing an error.

Please Note I have written this code in a .tsx file.

import React, {useState, useReducer,useEffect} from &quot;react&quot;
import {View, Text, StyleSheet, Image, Dimensions, TouchableOpacity} from &quot;react-native&quot;
import * as Location from &quot;expo-location&quot;
const screenWidth = Dimensions.get(&quot;screen&quot;).width
export const LandingScreen = () =&gt; {
const[errorMsg, setErrorMsg] = useState(&quot;&quot;)
const [address, setAddress] = useState&lt;Location.Address&gt;()
const [displayAddress, setDisplayAddress] = useState(&quot;Waiting for current location&quot;)
useEffect(() =&gt;{
(async () =&gt;{
let { status } = await Location.requestPermissionsAsync()
if(status !== &quot;granted&quot;){
setErrorMsg(
&quot;permissions not granted ,Allow the app to use location service&quot;
)
}
let location: any = await Location.getCurrentPositionAsync()
const {coords} = location
if(coords){
const{latitude, longitude} = coords;
let addressResponse: any = await Location.reverseGeocodeAsync({
latitude,
longitude
});
for(let item of addressResponse){
setAddress(item)
let currentAddress = `${item.name}, ${item.street}, ${item.postalCode}, ${item.city}`
setDisplayAddress(currentAddress)
/*if(address.length &gt; 0){
setTimeout(()=&gt;{
navigate(&quot;HomeScreen&quot;)
},1000)
}*/
}
}
})
},[])
return(
&lt;View style={styles.container}&gt;
&lt;View style={styles.navigation}/&gt;
&lt;View style={styles.body}&gt;
&lt;Image source={require(&quot;../images/delivery.png&quot;)} style={styles.deliveryIcon}/&gt;
&lt;View style={styles.addressContainer}&gt;
&lt;Text style={styles.addressTitle}&gt;Your deliver address&lt;/Text&gt;
&lt;/View&gt;
&lt;Text style={styles.addressText}&gt;{displayAddress}&lt;/Text&gt;
&lt;/View&gt;
&lt;View style={styles.footer}/&gt;
&lt;/View&gt;
)
}
const styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:&#39;rgba(242,242,242,1)&#39;
},
navigation:{
flex:2,
},
body:{
flex:9,
justifyContent:&quot;center&quot;,
alignItems:&quot;center&quot;,
},
footer:{
flex:1,
},
deliveryIcon:{
width:120,
height:120
},
addressContainer:{
width:screenWidth - 100,
borderBottomColor:&quot;red&quot;,
borderBottomWidth:0.5,
padding:5,
marginBottom:10,
alignItems:&quot;center&quot;
},
addressTitle:{
fontSize:24,
fontWeight:&quot;700&quot;,
color:&quot;#7D7D7D&quot;
},
addressText:{
fontSize:20,
fontWeight:&quot;200&quot;,
color:&quot;#4F4F4F&quot;
}
})

答案1

得分: 0

  1. let { status } = await Location.requestForegroundPermissionsAsync(); 代替 let { status } = await Location.requestPermissionsAsync();

  2. 删除这部分 &lt;Location.Address&gt;,应该是 const [address, setAddress] = useState()

英文:
  1. Insted of
    let { status } = await Location.requestPermissionsAsync()
    use
    let { status } = await Location.requestForegroundPermissionsAsync();

2.
remove this &lt;Location.Address&gt; it should be const [address, setAddress] = useState()

答案2

得分: 0

  1. 正如 @komal-harmale 提到的,使用 [address, setAddress] = useState()

  2. 在 Location.Address 中显示地址模块未加载。

    Location.requestPermissionsAsync() 已被弃用。https://docs.expo.dev/versions/latest/sdk/location/#locationrequestpermissionsasync

    在这种情况下,你需要使用 requestForegroundPermissionsAsyncrequestBackgroundPermissionsAsync 来代替它。

    我也遇到了相同的情况,我通过使用 requestForegroundPermissionsAsyncrequestBackgroundPermissionsAsyncModal 来解决了这个问题。我会简要解释我做了什么。

    1. 在你想要请求权限的地方初始化这些状态变量。
    const [foreground, requestForeground] = ExpoLocation.useForegroundPermissions();
    const [background, requestBackground] = ExpoLocation.useBackgroundPermissions();
    

    1. 使用前面提到的状态对象创建一个 Modal。以下是一个从用户那里请求权限的示例 Modal。
    import { Button, Linking, Modal, StyleSheet, Text, View } from "react-native";
    
    export const LocationRequestModal = ({ foreground, requestForeground, background, requestBackground }) => {
      return (
        <Modal visible={foreground && !foreground.granted && background && !background.granted}>
          <View style={Styles.backDrop}>
            <View style={Styles.middleView}>
              <View style={{ marginVertical: 16 }}>
                <Text style={{ fontSize: 20, fontWeight: "bold" }}>请授予权限</Text>
              </View>
              <View style={{ marginVertical: 16 }}>
                <Text style={{ fontSize: 18 }}>前台权限</Text>
                <Text>状态: {foreground?.status || "等待"}</Text>
                {foreground && !foreground.granted && foreground.canAskAgain && <Button title="授予权限" onPress={requestForeground} />}
                {foreground && !foreground.granted && !foreground.canAskAgain && (
                  <Button
                    title="通过设置授予权限"
                    onPress={() => requestForeground().then((p) => !p.granted && Linking.openSettings())}
                  />
                )}
              </View>
    
              <View style={{ marginVertical: 16 }}>
                <Text style={{ fontSize: 18 }}>后台权限</Text>
                <Text>状态: {background?.status || "等待"}</Text>
                {!foreground?.granted && <Text>首先授予前台位置权限</Text>}
                {foreground?.granted && background && !background.granted && background.canAskAgain && (
                  <Button title="授予权限" onPress={requestBackground} />
                )}
                {foreground?.granted && background && !background.granted && !background.canAskAgain && (
                  <Button
                    title="通过设置授予权限"
                    onPress={() => requestBackground().then((p) => !p.granted && Linking.openSettings())}
                  />
                )}
              </View>
            </View>
          </View>
        </Modal>
      );
    };
    
    const Styles = StyleSheet.create({
      backDrop: {
        backgroundColor: "rgba(52, 52, 52, 0.8)",
        height: "100%",
        width: "100%",
        paddingBottom: "3%",
        paddingTop: "3%",
        paddingRight: "6%",
        paddingLeft: "6%",
        justifyContent: "center",
        alignItems: "center",
      },
      middleView: { height: "60%", width: "60%", backgroundColor: "white", justifyContent: "center", alignItems: "center" },
    });
    
英文:
  1. as @komal-harmale mentioned use the [address, setAddress] = useState()
  2. In Location.Address it is showing that address module is not loaded.
    <br><br>
    Location.requestPermissionsAsync() has been deprecated. https://docs.expo.dev/versions/latest/sdk/location/#locationrequestpermissionsasync
    <br>In that case you have to use In that case you have to use requestForegroundPermissionsAsync or requestBackgroundPermissionsAsync instead of that.
    <br>
    <br>
    Same scenario happened to me and I overcame that by using requestForegroundPermissionsAsync, requestBackgroundPermissionsAsync and with a help of Modal. will explain briefly what I did.
    <br>
    <br>
    1 . initialize these states variables where you wants to request permissions.
  const [foreground, requestForeground] = ExpoLocation.useForegroundPermissions();
  const [background, requestBackground] = ExpoLocation.useBackgroundPermissions();

<br><br>
2 . Create a Modal with the use of earlier mentioned state objects. Here is a sample Modal to request permissions from user. <br>

import { Button, Linking, Modal, StyleSheet, Text, View } from &quot;react-native&quot;;

export const LocationRequestModal = ({ foreground, requestForeground, background, requestBackground }) =&gt; {
  return (
    &lt;Modal visible={foreground &amp;&amp; !foreground.granted &amp;&amp; background &amp;&amp; !background.granted}&gt;
      &lt;View style={Styles.backDrop}&gt;
        &lt;View style={Styles.middleView}&gt;
          &lt;View style={{ marginVertical: 16 }}&gt;
            &lt;Text style={{ fontSize: 20, fontWeight: &quot;bold&quot; }}&gt;Pleae grant permission.&lt;/Text&gt;
          &lt;/View&gt;
          &lt;View style={{ marginVertical: 16 }}&gt;
            &lt;Text style={{ fontSize: 18 }}&gt;Foreground permission:&lt;/Text&gt;
            &lt;Text&gt;status: {foreground?.status || &quot;pending&quot;}&lt;/Text&gt;
            {foreground &amp;&amp; !foreground.granted &amp;&amp; foreground.canAskAgain &amp;&amp; &lt;Button title=&quot;Grant permission&quot; onPress={requestForeground} /&gt;}
            {foreground &amp;&amp; !foreground.granted &amp;&amp; !foreground.canAskAgain &amp;&amp; (
              &lt;Button
                title=&quot;Grant permission through settings&quot;
                onPress={() =&gt; requestForeground().then((p) =&gt; !p.granted &amp;&amp; Linking.openSettings())}
              /&gt;
            )}
          &lt;/View&gt;

          &lt;View style={{ marginVertical: 16 }}&gt;
            &lt;Text style={{ fontSize: 18 }}&gt;Background permission:&lt;/Text&gt;
            &lt;Text&gt;status: {background?.status || &quot;pending&quot;}&lt;/Text&gt;
            {!foreground?.granted &amp;&amp; &lt;Text&gt;Grant foreground location permission first&lt;/Text&gt;}
            {foreground?.granted &amp;&amp; background &amp;&amp; !background.granted &amp;&amp; background.canAskAgain &amp;&amp; (
              &lt;Button title=&quot;Grant permission&quot; onPress={requestBackground} /&gt;
            )}
            {foreground?.granted &amp;&amp; background &amp;&amp; !background.granted &amp;&amp; !background.canAskAgain &amp;&amp; (
              &lt;Button
                title=&quot;Grant permission through settings&quot;
                onPress={() =&gt; requestBackground().then((p) =&gt; !p.granted &amp;&amp; Linking.openSettings())}
              /&gt;
            )}
          &lt;/View&gt;
        &lt;/View&gt;
      &lt;/View&gt;
    &lt;/Modal&gt;
  );
};

const Styles = StyleSheet.create({
  backDrop: {
    backgroundColor: &quot;rgba(52, 52, 52, 0.8)&quot;,
    height: &quot;100%&quot;,
    width: &quot;100%&quot;,
    paddingBottom: &quot;3%&quot;,
    paddingTop: &quot;3%&quot;,
    paddingRight: &quot;6%&quot;,
    paddingLeft: &quot;6%&quot;,
    justifyContent: &quot;center&quot;,
    alignItems: &quot;center&quot;,
  },
  middleView: { height: &quot;60%&quot;, width: &quot;60%&quot;, backgroundColor: &quot;white&quot;, justifyContent: &quot;center&quot;, alignItems: &quot;center&quot; },
});

huangapple
  • 本文由 发表于 2023年2月18日 20:34:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定