我正在制作一个我必须从API获得结果的项目。 我有一个问题,因为当我的查询结果为空时,则会发生错误:
`Book.js:10 Uncaught(in promise)TypeError:无法读取属性' thumbnail'未定义'
这是我在搜索组件中的代码:
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import escapeRegExp from 'escape-string-regexp'
import Book from './Book'
import * as BooksAPI from './BooksAPI'
class SearchView extends Component {
state = {
query: '',
books: [],
filteredBooks: []
}
updateQuery = (query) => {
this.setState({query})
if(query){
BooksAPI.search(query).then((books) => {
if(books instanceof Array) {
//add books to state
this.setState({books})
//filter array
const match = new RegExp(escapeRegExp(query))
const filteredBooks = this.state.books.filter((book) => match.test(book.title) || match.test(book.title))
this.setState({books: filteredBooks})
}
else {
//set book state to empty array
this.setState({books: []})
}
}
)
}
}
render() {
const {onChangeCategory} = this.props
const {query, books} = this.state
return (
<div>
<div className="search-books-bar">
<Link className="close-search" to="/">Close</Link>
<form>
<div className="search-books-input-wrapper">
<input type='text' placeholder='Search books by title or author' value={query} onChange={(event) => this.updateQuery(event.target.value)} />
</div>
</form>
</div>
{books.length!==0 && (
<div className="search-books-results">
<div className="search-books">
<ol className="books-grid">
{books.map((book) => (
<li key={book.id}>
<Book
onChangeCategory={onChangeCategory}
book = {book}
/>
</li>
))}
</ol>
</div>
</div>
)}
{(books.length===0 && query.length!==0) && (
<div className="search-results">
{`No book found`}
</div>
)}
</div>
)
}
}
export default SearchView
也许有些人可以给我一个提示,我必须在此代码中添加或更改以解决此问题......
以下是此项目的存储库链接:enter link description here 谢谢你的回答:)
答案 0 :(得分:0)
你甚至可以这样做:
subscribe