我有一个BooksAPI文件,其中包含以下搜索方法:
export const search = (query) =>
fetch(`${api}/search`, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json'
},
body: JSON.stringify({ query })
}).then(res => res.json())
.then(data => data.books)
我正在尝试将其设置为当我在搜索栏中输入时结果开始显示,并且我还希望在搜索栏为空时不显示任何书籍。
我有它工作,以便我可以使用初始搜索显示结果,但如果我尝试退格键入新术语,我会收到cannot read property map of undefined
错误,这是有道理的,但我不是确定如何解决这个问题。如果我刷新页面,我只能进行新的搜索。
非常感谢任何帮助。
这是我到目前为止App.js:
class BooksApp extends React.Component {
state = {
books: []
}
componentDidMount() {
BooksAPI.getAll()
.then((books) => {
this.setState(() => ({
books
}))
})
}
render() {
return (
<div className="app">
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
<Route exact path="/" render={() => (
<BookList
books={this.state.books}
/>
)} />
<Route path="/search" component={Search} />
<Route path="/search" render={({ history }) => (
<Search
onSearch={(query) => {
this.search(query)
history.push('/')
}}
/>
)} />
<div className="open-search">
<Link to="/search">Add a book</Link>
</div>
</div>
</div>
)
}
}
export default BooksApp
这是我的搜索组件:
class Search extends Component {
state = {
query: '',
books: []
}
search = (query) => {
BooksAPI.search()
.then((books) => {
this.setState(() => ({
query,
books
}))
})
}
render() {
const { query, books } = this.state
return (
<div className="search-books">
<div className="search-books-bar">
<Link
className="close-search"
to='/'>Close
</Link>
<div className="search-books-input-wrapper">
<input
type="text"
onChange={(event) => this.search(event.target.value)}
placeholder="Search by title or author"
value={query}
/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{books.map((book) => (
<li>
<div>
<p>{book.title}</p>
<p>{book.author}</p>
</div>
</li>
))}
</ol>
</div>
</div>
)
}
}
export default Search;