在 react-native(fetch、axios 等)中进行一次 API 调用的最佳方法?

Best way to make exactly one API call in react-native (fetch, axios etc.)?

我目前正在创建一个包含条形码扫描仪的应用程序。不幸的是,我发现的唯一一家公司——似乎拥有所有食品条形码的 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 });
      }
    }

如果您尝试使用 4015000961547keyValue,您将得到 Henkel AG,以防您想要测试 (http://gepir.gs1.org/index.php/search-by-gtin)。我不明白的是:尽管我正在使用 async/ await,为什么我的函数会在条形码被读取后向 API 发出如此多的请求?我读到 axios 是更好的方法,但它在我的情况下并没有真正起作用......我可以尝试第三种/第四种方法吗?非常重要的是,一旦我有了扫描数据,我只向 API 发送 one 请求,否则我无法测试它。

只是为了提供所有需要的信息,这是我在扫描后获取条形码数据的代码。我正在使用 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>
    );
  }
}

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

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

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