搜尋

首頁  >  問答  >  主體

如何在React Native中將資料傳遞到後端

我正在嘗試為IOS 開發一個條碼掃描器應用程序,現在我已經設法創建一個可以從條碼讀取數據的掃描儀,但不僅僅是讀取數據,我還想將數據存儲到數據庫中,我已經探索了一些另一邊的原始程式碼是我的程式碼。

掃描器.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, setText] = 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);
     
     
     setText(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>)
  }
 
  // 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})} /> 
         
      }
    </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'
  }
});

在我探索了將資料傳送到後端的方法之後,它需要這種程式碼,但是我該如何將此程式碼實作到我的scanner.js中?希望大家幫忙謝謝

export default class Scanner extends Component {

  constructor(props) {
    super(props);
    this.state = {userid: ''};
  }

  Register = () => {
    let userid = this.state.userid;
    

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

      let headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      };

      let Data = {
        userid: userid,
       
      };

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

P粉878542459P粉878542459273 天前394

全部回覆(1)我來回復

  • P粉770375450

    P粉7703754502024-03-30 08:00:07

    在我嘗試在scanner.js中實作它之後就OK了

    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, setText] = 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);
         
         
         setText(data )
         
       
      };
      Register = () => {
        this.state={
            userid:''
        };
        let userid = this.state.userid;
        
    
        
          let InsertAPIURL = "https://127.0.0.1/api/insert.php";
    
          let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          };
    
          let Data = {
            userid: userid,
           
          };
    
          fetch(InsertAPIURL, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(Data)
          })
          .then((response) =>response.json())
          .then((response)=>{
            alert(response[0].Message);
          })
          .catch((error) => {
            alert("Eror"+error);
          })
        
      }
    
     
      // Check permissions and return the screens
      if (hasPermission === null) {
        return (
          
            Requesting for camera permission
          )
      }
      if (hasPermission === false) {
        return (
          
            No access to camera
            

    插入.php

     $Message);
        echo json_encode($Response);
    ?>

    我掃描條碼並點擊「確定」按鈕後顯示錯誤 類型錯誤:網路請求失敗

    #

    回覆
    0
  • 取消回覆