使用ISBN从Google Books API获取书名

时间:2018-07-10 21:29:54

标签: javascript json react-native fetch-api google-books

我对Javascript和React-Native非常陌生,并且正在构建一个非常简单的应用程序,它可以扫描书的条形码中的ISBN,然后将其与书名匹配。

我认为我已经设法获得了ISBN号,并试图从google-books API中获取书名,但我不断收到错误消息“未定义不是一个对象(正在评估'_this.state.results.items [0] .title)”。谁能帮助我找出问题所在以及可以采取哪些步骤加以解决?谢谢!抱歉,如果有很多错误或者我的代码很糟糕。我真的很新,感谢您的帮助!

import React from 'react';
import { Dimensions, StyleSheet, Text, View } from 'react-native';
import { BarCodeScanner } from 'expo';

const { width } = Dimensions.get('window');

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.state= {
      results: {
        kind: '',
        totalItems: 0,
        items: []
      }
    }
    this.fetchData = this.fetchData.bind(this);
  }


  fetchData(isbn) {
    fetch(`https://www.googleapis.com/books/v1/volumes? 
   q=isbn:${encodeURIComponent(isbn)}`)
    .then((response)=> response.json())
    .then((responseData)=> {
      this.setState({results: responseData})
    });

  }

  _handleBarCodeRead = ({ type, data }) => {
    var isbn = data;
    this.fetchData(isbn)
    var title = this.state.results.items[0].volumeInfo.title;
    alert(`ISBN: ${isbn}, Title: ${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>
    );
  }
}

编辑:因此,我在URL中缺少“ isbn:”,这导致我获得了不正确的书名。我已解决此问题,现在在警报中,我获得了与ISBN相匹配的正确书名。但是,即使我收到警报,仍然具有相同的未定义对象(评估'_this.state.results.items [0] .title)

2 个答案:

答案 0 :(得分:0)

您似乎试图在错误的位置获取title属性。

尝试更改为var title = this.state.results.items[0].volumeInfo.title;

enter image description here

答案 1 :(得分:0)

您有比赛条件。 警报在执行setState之前发生。解决此问题的一种方法是使用callback()

  fetchData(isbn, callback) {
    fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${encodeURIComponent(isbn)}`)
        .then(response => response.json())
        .then(responseJson => {
            this.setState({ bookInfo: responseJson.items[0].volumeInfo.title});
            callback();
        })
    .catch(error => {
      console.error(error);
    });
  }

  alertInfo = () => {
      var title = this.state.bookInfo;
      alert(`Title: ${title} was scanned!`);
  }


  handleBarCodeScanned = ({ data }) => {
    var isbn = data;
    this.setState({ scanned: true });
    this.fetchData(isbn, this.alertInfo);
  };