【问题标题】:Fetching Book Title from Google Books API with ISBN使用 ISBN 从 Google Books API 获取书名
【发布时间】:2018-12-18 19:50:29
【问题描述】:

我对 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>
    );
  }
}

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

【问题讨论】:

  • 听起来第一项缺少标题。你试过检查fetch返回的数据吗?
  • 你在尝试什么 ISBN?
  • 如果将.then((responseData)=&gt; {this.setState({results: responseData})}); 更改为.then((responseData)=&gt; { console.log('responseData', responseData); this.setState({results: responseData})});,您会看到什么?你会在控制台的某个地方看到这个。我很担心,因为您最初将您的 results 状态定义为一个对象,但您可能会从 API 调用中以数组的形式收到您的 results
  • 所以我进行了您建议的更改,在我的控制台中,我看到了一个 LONG JSON 对象,其中包含许多书籍的详细信息,而不仅仅是我希望找回的一个标题

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢,是的,我只是在你说之后才注意到。现在我的警报显示了一个标题,但由于某种原因它不是我正在扫描的书的标题。虽然它显示的标题是同一作者的
  • 另外,即使我的警报消息显示 ISBN 和书名,我仍然收到相同的 undefined is not an object 错误消息
【解决方案2】:

你有一个竞争条件。 警报发生在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);
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多