繁体   English   中英

在设备上运行时反应本机应用程序出错

[英]react native app having error when run on device

当我使用 web 执行程序时,我通过使用 react native 实现了一个条形码扫描仪应用程序,所有功能都可以完美运行它可以将数据传递给 api 并发布到服务器但是当我尝试在我的 android 和 iOS 设备上使用它时它不能发布下面的数据是我的scanner.js代码

import React, { useState, useEffect,Component,onMount} from 'react';
import { Text,TextInput, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import {useNavigation} from'@react-navigation/native';
import {StatusBar} from 'expo-status-bar';





  export default function Scanner () {
  
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);
  const [userid, setuserid] = useState('Not yet scanned')
  const [currentDate, setCurrentDate] = useState('');
  const navigation = useNavigation();


  const askForCameraPermission = () => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })()
  }

  // Request Camera Permission
  useEffect(() => {
    askForCameraPermission();
  }, []);

  useEffect(() => {
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    setCurrentDate(
      date + '/' + month + '/' + year 
      + ' ' + hours + ':' + min + ':' + sec
    );
  }, []);
  // What happens when we scan the bar code

  const handleBarCodeScanned = ({ type, data }) => {

   
    setScanned(true);
     
     
     setuserid(data )
     
   
  };
 
  // Check permissions and return the screens
  if (hasPermission === null) {
    return (
      <View style={styles.container}>
        <Text>Requesting for camera permission</Text>
      </View>)
  }
  if (hasPermission === false) {
    return (
      <View style={styles.container}>
        <Text style={{ margin: 10 }}>No access to camera</Text>
        <Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
      </View>)
  }

   
   const Register = () => {

    
   
    let InsertAPIURL = "https://localhost/api/insert.php";

      let headers = {
        
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Methods': 'POST, PUT, PATCH, GET, DELETE, OPTIONS',

        'Access-Control-Allow-Headers': 'Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization',
      }
      let Data = {
        userid:userid,
        
      };

      fetch(InsertAPIURL, {
        mode:'no-cors',
        method: 'POST',
        headers: headers,
        body: JSON.stringify(Data)
      })
      try{
        ((response) =>response.json()),
      ((response)=>{
        alert(response[0].Message);
      })
      }
      
      catch{
        ((error) => {
        alert("Error"+error);
      })
    } }

  // Return the View
  return (
     
    <View style={styles.container}>
      <View style={styles.barcodebox}>
        <BarCodeScanner
          onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
          style={{ height: 400, width: 400 }} />
      </View>
      
      <Text style={styles.maintext}>{userid + '\n'+currentDate}
    
      </Text>

      
      {
        scanned && <Button title={'Scan again?'} onPress={() => setScanned(false)} color='tomato' />
         
      }
     
      {
         scanned && <Button title={'OK'} onPress={()=> navigation.navigate('Home',{userid},Register())} />
         
      }
    </View>
  );
}



const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  maintext: {
    fontSize: 16,
    margin: 20,
  },
  barcodebox: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 300,
    width: 300,
    overflow: 'hidden',
    borderRadius: 30,
    backgroundColor: 'tomato'
  }
});

我对其他来源进行了研究,他们说将 apiurl 更改为http://10.0.2.2而不是 localhost 主机以使其在 android 设备上运行,但是在我尝试了这种方法之后它也无法解决问题。 这是我的第一个反应原生项目,我真的坚持了几天已经希望你们帮助提前谢谢

您需要提供您的 ip 地址而不是localhost ,您可以通过在 linux/Mac 上执行ifconfig和在 windows 上执行ipconfig来找到它。

所以你有这样的东西: 192.0.0.1:3000/yoururl而不是localhost:3000/yoururl

仅当您想在连接到计算机的真实设备上进行测试时才需要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM