发送多个重复的 PUT 请求

mc2017

我正在为课堂工作的这个应用程序的一部分应该是扫描一本书的条形码(使用 expo XDE 条形码扫描仪组件),然后将扫描的条形码发送到我班上另一个小组正在处理的数据库中。我现在的问题是,每次进行扫描时,我都会在控制台中看到我正在发送多个重复的 PUT 请求。我认为问题在于 expo 条码扫描仪不只是扫描一次然后停止,而是继续扫描,每次扫描时,我的状态都会“更新”并且组件会重新呈现。有没有人对我如何修改我的代码以确保我不会使用相同的数据一遍又一遍地重新渲染有任何建议?我在下面包含了相关代码。注意:为了测试目的,一些数据是硬编码的。谢谢!

class SecondScreen extends Component {

  constructor(props) {
    super(props);

    this.state= {
        results: []
    }
    this.fetchData = this.fetchData.bind(this);

  }

  fetchData(URL) {
    return fetch(URL)
      .then((response) => response.json())
      .then((responseData) => {
        return responseData 
      })
      .catch((error) => {
        console.error(error)
      })
  }


_handleBarCodeRead = data => {
    let isbn = data.data; 
    let URL = 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + 
    isbn;


    this.fetchData(URL).then(bookResult => {

      this.setState({ results: bookResult }

      fetch('https://p0kvnd5htd.execute-api.us-east- 
           2.amazonaws.com/test/return', {
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({

        'libraryName': 'lib1', //libName
        'bookBarcode': '18263' //isbn
      }),
    })

      .then((response) => {
        if (response.status == 400) {
          console.log(response.status)

          alert('Return unsuccessful, please try again.');
        }
        else {
          console.log(response.status)
          this.props.navigation.navigate('ThirdPage', { title: 
          this.state.results.items[0].volumeInfo.title });
        }
      })
    })
  }

  render() {
    return (
      <BarCodeScanner
        onBarCodeRead={this._handleBarCodeRead}
        style={[StyleSheet.absoluteFill, styles.container]}
      >
        <View style={styles.layerTop} />
        <View style={styles.layerCenter}>
          <View style={styles.layerLeft} />
          <View style={styles.focused} />
          <View style={styles.layerRight} />
        </View>
        <View style={styles.layerBottom} />
      </BarCodeScanner>
    );
  }
}
基础

简单的解决方法是使用 lodash 的去抖动功能:

命令行: npm i lodash

javascript的顶部:

import _ from 'lodash'

将 _handleBarCodeRead 包裹在 debounce 中,这将防止 _handleBarCodeRead 在最后一次调用后的 3 秒内被多次调用:

_debouncedHandleBarCodeRead = _.debounce((data) =>{ this._handleBarCodeRead(data) }, 3000, {leading: true, trailing: false});

将 BarCodeScanner 更改为使用去抖动方法:

<BarCodeScanner onBarCodeRead={this._debouncedHandleBarCodeRead} >

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章