在react-native(fetch,axios等)中准确进行一个API调用的最佳方法?

时间:2019-02-19 23:57:13

标签: reactjs api react-native async-await react-native-camera

我当前正在创建一个包含条形码扫描仪的应用程序。不幸的是,我发现的唯一一家似乎拥有所有食品条形码90%以上的公司提供的API起价为每年500美元。因此,我试图创建一种可行的解决方法,但会触发许多API调用,因此我尝试一次后立即将其阻止。我插入了console.warn,以查看每次调用API时会触发多少次调用,大约是20到35次。这是代码:

    async getApiData() {
      let formData = new FormData();
      formData.append('keyValue', 4015000961547);
      formData.append('requestTradeItemType', 'ownership');
      formData.append('keyCode', 'gtin');
      formData.append('someRandomToken', '1');
      const response = await fetch('http://gepir.gs1.org/index.php?option=com_gepir4ui&view=getkeylicensee&format=raw', {
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Cookie': 'someRandomCookie'
        },
        body: formData
      });
      if (response.status == 200) {
        const responseJson = JSON.parse(response._bodyText);
        const productName = responseJson.gepirParty.partyDataLine.gS1KeyLicensee.partyName;
        this.setState({ productName });
      }
    }

如果您对此keyValue中的4015000961547进行尝试,您将得到Henkel AG,以备测试(http://gepir.gs1.org/index.php/search-by-gtin)。我不明白的是:为什么在我完全使用async/ await读取条形码后,为什么我的函数向API发出了这么多请求?我读到axios是更好的方法,但是在我的情况下并没有真正起作用……我可以尝试第三种还是第四种方法?至关重要的是,一旦获得扫描数据,我只会向API发送一个请求,否则我将无法对其进行测试。

仅提供所有需要的信息,这是我在扫描后获取条形码数据的代码。我正在使用react-native-camera

import { RNCamera } from 'react-native-camera';
... some more code ...

export default class Scanner extends Component {
  ... some code ...

   async onBarCodeRead(scanResult) {
    console.warn(scanResult.type);
    if (scanResult.data != null) {
      console.warn(scanResult.data);
      const eanCode = await scanResult.data;
    }
    return;
  }
  ...some code here...

  render() {
    return (
      <View>
        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          barcodeFinderVisible={this.state.camera.barcodeFinderVisible}
          defaultTouchToFocus
          mirrorImage={false}
          onBarCodeRead={this.onBarCodeRead.bind(this)}
          onFocusChanged={() => {}}
          onZoomChanged={() => {}}
          type={this.state.camera.type}
        />
        <View>
          <Text>Please scan the barcode.</Text>
        </View>
      </View>
    );
  }
}

为简单起见,我删除了props标签中的所有样式和未使用的RNCamera

1 个答案:

答案 0 :(得分:1)

这似乎是一项功能-它会连续扫描条形码。 回购上有一个issue thread,建议您在第一次发出事件时设置一个标志,例如:

onBarCodeRead = (...someArgs) => {
  if (!this.isBarcodeRead) {
     this.isBarcodeRead = true;
     // Do your work
  }
}