我正在尝试实现一个书架,有不同书架上的书,当我搜索已经在书架上的书时,搜索组件应该更新并发现它已经在书架上。
这是我的代码
import { Link } from 'react-router-dom'
import * as BooksAPI from './BooksAPI'
import { PropTypes } from 'prop-types'
import Book from './Book'
import React, {Component} from 'react'
import _ from 'lodash'
class BookSearch extends Component {
state = {
books: [],
changes: ''
}
addBook = (book, shelf) => {
this.props.onChange(book, shelf)
this.props.history.push('/')
}
fixChange = (event) => {
let eValue = event.target.value
this.setState(() => {
return {changes: eValue}
})
this.searchBooks(eValue)
}
clearBooks = () => {
this.setState({books: [], changes: ''})
}
noBooks = _.debounce((changes) => {
BooksAPI.search(changes).then(booksResponse => {
if (booksResponse.error) {
return this.setState({books: []});
}
})
})
matchBookShelf = (query) =>{
BooksAPI.search(query,30).then((books) => {
const results = books.map((book) => {
const existingBook = this.state.books.find((b) => b.id === book.id)
book.shelf = !!existingBook ? existingBook.shelf : 'none'
return book
});
}
)
}
findBooks = (i) => {
BooksAPI.search(i).then((books) => {
if (books.length > 0) {
this.setState(() => {
return {
books: books.filter((book) => (book.imageLinks))
}
})
}
})
}
searchBooks = (value) => {
if (value.length !== 0) {
this.findBooks(value);
this.noBooks(value);
}
else {
this.clearBooks()
}
}
bookGrid = () => {
return (
<div className="books-grid">
{this.state.changes.length > 0 && this.state.books.map((book, index) =>
(<Book book={ book } key={ index } onUpdate={(shelf) => {
this.addBook(book, shelf)
}}/>))}
</div>
)
}
render() {
return (
<div className="search-books">
<div className="search-books-bar">
<Link to='/' className="close-search">Close</Link>
<div className="search-books-input-wrapper">
<input type="text" placeholder="Libary" value={ this.state.changes } onChange={ this.fixChange }/>
</div>
</div>
<div className="search-books-results">
{this.bookGrid()}
</div>
</div>
)
}
}
export default BookSearch;
有人告诉我,这应该对我有帮助
BooksAPI.search(query,30).then((books) => {
if(!!books){
if(books.length>0){
const results = books.map((book) => {
const existingBook = this.state.books.find((b) => b.id === book.id)
book.shelf = !!existingBook ? existingBook.shelf : ‘none’
return book
});
this.setState({ results })
}
}
})
我不太了解如何实施更改。其他所有内容均按预期工作。架子和搜索架子之间的ID应该匹配。