Использование Expo Barcode Scanner для извлечения данных из REST API в React Native - PullRequest
0 голосов
/ 24 февраля 2020

Я создаю приложение React Native, которое сканирует QR-код и затем извлекает данные из REST API (написано в Java) на основе этого QR-кода. С другой стороны, этот QR-код будет декодирован как ID, и он получит данные из базы данных по этому ID через API REST. Как мне разработать приложение React Native App и REST API? Пока что я написал эти коды:

Это мое приложение. js:


'use strict'

import React, { Component, useState, useEffect }  from 'react';
import Artifact from "./components/Artifact";
import axios from 'axios';
import ArtifactList from "./components/ArtifactList";
import { BarCodeScanner } from 'expo-barcode-scanner';
import QRCodeScanner from "./components/QRCodeScanner";

import {
  AppRegistry,
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  Button,
  StatusBar,
  TouchableOpacity,
  Linking,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';


class App extends Component {

  // default State object
  state = {
    artifacts: []
  };
  componentDidMount() {
    axios
      .get("http://10.40.38.192:8080/mues/rest/jsonServices")
      .then(response =>
        Object.keys(response.data).map(e => ({
            key: `${e.id}`,
            inventoryNo: `${e.inventoryNo}`
        }))
        )
        .then(artifacts => {
            this.setState({
                artifacts
            });
        })
      .catch(error => console.log(error));
  }

  render() {
    return (
    <>
        <View>
          <ArtifactList artifacts={this.state.artifacts} />
        </View>

        <View
          style={{
            flex: 1,
            flexDirection: 'column',
            justifyContent: 'flex-end',
          }}>
          <QRCodeScanner />
        </View> 
    </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
});

export default App;

ArtifactList. js:

import React from "react";

import Artifact from "./Artifact ";
import { View, Text } from 'react-native';

function ArtifactList(props) {
  return (
    <View>
        {props.artifacts.map(e => <Artifact key={e.id} inventoryNo={e.inventoryNo} />)}
    </View>
  );
}

export default ArtifactList;

Артефакт. js:

import React from 'react';
import PropTypes from 'prop-types';
import { View, Text, StyleSheet } from 'react-native';

function Artifact(props) {
  return (
    <View>
        <Text style={styles.artifact}> Artifact Information: {props.inventoryNo}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  artifact: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
});


export default Artifact;

QRCodeScanner. js:

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';

export default function QRCodeScanner() {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  useEffect(() => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

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


    setScanned(true);
    alert(`Bar code with type ${type} and data ${data} has been scanned!`);
  };

  if (hasPermission === null) {
    return <Text>Requesting for camera permission</Text>;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'flex-end',
      }}>
      <BarCodeScanner
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />
      {scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
    </View>
  );
}

И, наконец, вот результат json моего REST API:

{"id":3,"aktif":true,"silinmis":false,"eserId":"G.3","permanentId":null,"versiyon":null,"pieces":null,"genelAciklama":null,"envanterNo":"ak44","tasinirIslemFisiNo":null,"eserOzelAdi":null,"uretimYili":null,"sikke":false,"uniklikDurumu":false,"torenselDurumu":false,"updateInProgress":false,"eserForLab":false,"termStart":null,"termEnd":null,"kiymet":null,"createSessionId":null,"dateCreated":null,"dateUpdated":null,"dateDeleted":null,"silmeAciklamasi":null,"envanterDefteriPath":null,"envanterFishiPath":null,"qrCode":null,"eserKeywords":null,"eserKaynakLiteraturs":null,"eserYayinLiteraturs":null,"eserMeasures":null,"eserSerhs":null,"eserDepos":null,"eserZimmets":null,"eserCizims":null,"eserFotografs":null,"anaFotograf":null,"transcriptions":null,"eserMalzemeYapimTeknigis":null,"eserMalzemeSuslemeTeknigis":null,"eserHarekets":null,"eserStils":null,"eserAtolyes":null,"kondisyonDurumu":null,"sikkeDarpYonu":null,"yazmaBasmaSecimi":null,"islamiGayriSecimi":null,"elisiDokumaSecimi":null,"eserAltTur":null,"iliskilendirme":null,"birlestirme":null,"cag":null,"donem":null,"uygarlik":null,"hukumdar":null,"tasinirMalYonKod":null,"updatedBy":null,"deletedBy":null,"createdBy":null,"onaylayanKullanici":null,"bagislayanVip":null,"yaptiranVip":null,"yapanVip":null,"kullanacakVip":null,"kullananVip":null,"uretimYeri":null,"uretimBolgesi":null,"darpYeri":null,"signumStart":null,"signumEnd":null,"signumUretim":null,"name":"3","termEndTitle":null,"title":"G.3 null","eserDepo":null,"assetId":null,"tempId":"G.3","oneId":"G.3","significantUretim":null,"uretimYiliTitle":null,"termStartTitle":null,"significantEnd":null,"significantStart":null}

Я хочу получить все данные, опубликованные в виде Json данных, с помощью QR-кода и просматривать / распечатывать их в React Native Application. Заранее благодарю за помощь.

...