在React组件中哪里获取数据

时间:2018-08-06 02:05:31

标签: javascript reactjs

我想对前端开发新手的Reactjs有所了解。 Google图书API很简单,因此我决定使用它来构建一个反应页面,该页面列出用户输入的10本书。

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';

const GOOGLE_BOOKS_API = 'https://www.googleapis.com/books/v1/volumes?q=';
const GOOGLE_BOOKS_API_LIMIT = 'maxResults=10';

class BookItem extends React.Component {
  render() {
    return (
      <div>
      <img alt="Book" src={this.props.data.volumeInfo.imageLinks.thumbnail} />
      <span>{this.props.data.volumeInfo.imageLinks.thumbnail}</span>
      </div>
    );
  }
}

class BookResults extends React.Component {
  render() {
    const isBookResultsEmpty = !(this.props.books && this.props.books.length > 1);
    const bookItems = isBookResultsEmpty ? [] : this.props.books.map((book,index) =>
      <BookItem key={index} data={book} />
    );
    return (
      <div className='book-results'>
        {isBookResultsEmpty ? (
          <h1>No Results</h1>
        ) : (
          <div> {bookItems} </div>
        )}
      </div>
    );
  }
}

class BookSearch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bookQuery: '',
      books: []
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.getBooks = this.getBooks.bind(this)
  }

  getBooks() {
    let queryString = '';
    if (this.state.bookQuery && this.state.bookQuery.length > 1) {
      queryString = this.state.bookQuery.replace(/\s/g, '+');
      fetch(`${GOOGLE_BOOKS_API}${queryString}&${GOOGLE_BOOKS_API_LIMIT}`)
      .then(results => {
        return results.json();
        })
      .then(json => {
        this.setState({
          books: json.items
        });
      })
      .catch(e => console.log('error', e));
    }
  }

  handleInputChange(event) {
    this.setState({
      bookQuery: this.search.value
    },
      this.getBooks());
  }

  render() {
    return (
      <div className="book-search">
        <form>
          <input
            placeholder="Search for Books"
            ref={input => this.search = input}
            onChange={this.handleInputChange}
          />
        </form>
        <BookResults books={this.state.books} />
      </div>
    );
  }
}

ReactDOM.render(<BookSearch />, document.getElementById('root'));

输入内容时出现错误:

  

TypeError:无法读取未定义的属性“缩略图”

我在BookResults组件中添加了对数据的检查,但仍然发生错误。我认为这与渲染时状态或props值的变化有关,但是我对React的了解不足以保证

1 个答案:

答案 0 :(得分:3)

有些书没有imageLinks,因此在使用前,请确保它不是undefined

示例

class BookItem extends React.Component {
  render() {
    const { imageLinks } = this.props.data.volumeInfo;

    if (!imageLinks) {
      return null;
    }

    return (
      <div>
        <img alt="Book" src={imageLinks.thumbnail} />
        <span>{imageLinks.thumbnail}</span>
      </div>
    );
  }
}