发送多个重复的PUT请求

时间:2018-08-24 17:40:07

标签: javascript react-native put expo

我正在上课的该应用程序的

部分应该是在扫描图书的条形码(使用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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

简单的解决方法是使用lodash的debounce函数:

命令行:npm i lodash

javascript顶部:

import _ from 'lodash'

将_handleBarCodeRead进行反跳处理,这将防止在最后一次调用后3秒钟内多次调用_handleBarCodeRead:

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

将BarCodeScanner更改为使用反跳方法:

<BarCodeScanner onBarCodeRead={this._debouncedHandleBarCodeRead} >