javascript - 将 setState 设置为搜索到的书籍数组,以便在无效查询的情况下将其返回空白数组
问题描述
对于 React 项目,如果查询无效,我必须将搜索到的书籍数组设置回空白数组,但目前我找不到解决问题的方法。
这是我的代码:
search_books = (val) => {
if (val.length !== 0 ) {
BooksAPI.search( val, 10 ).then((books) => {
if (books.length > 0 ) {
books = this.changeBookShelf(books)
this.setState(() => {
return {Books: books}
})
}
})
} else {
this.setState({Books: [], query: ''})
}
}
这是完整的代码,以防您需要它:
import React, {Component} from 'react'
import {Link} from 'react-router-dom'
import * as BooksAPI from '../BooksAPI'
import Book from './Book'
import {PropTypes} from 'prop-types'
class BookSearch extends Component {
state = {
Books: [],
query: ''
}
static propTypes = {
onChange: PropTypes.func.isRequired,
myBooks: PropTypes.array.isRequired
}
handleChange = ( event ) => {
var value = event.target.value
this.setState(() => {
return {query: value}
})
this.search_books(value)
}
changeBookShelf = ( books ) => {
let all_Books = this.props.myBooks
for ( let book of books ) {
book.shelf = "none"
}
for ( let book of books ) {
for ( let b of all_Books ) {
if ( b.id === book.id ) {
book.shelf = b.shelf
}
}
}
return books
}
search_books = (val) => {
if (val.length !== 0 ) {
BooksAPI.search( val, 10 ).then((books) => {
if (books.length > 0 ) {
books = this.changeBookShelf(books)
this.setState(() => {
return {Books: books}
})
}
})
} else {
this.setState({Books: [], query: ''})
}
}
add_book = ( book, shelf ) => {
this.props.onChange( book, shelf )
}
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="Search by title or author" value={this.state.query} onChange={this.handleChange}/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{this.state.query.length > 0 && this.state.Books.map((book, index) => (<Book book={book} key={index} onUpdate={(shelf) => {
this.add_book( book, shelf )
}}/>))}
</ol>
</div>
</div>
)
}
}
export default BookSearch;
这是最后一步,但如果在搜索栏中写入无效查询,我无法弄清楚如何使搜索启动错误。
解决方案
看起来您在没有查询时将其正确设置为空数组,但在有查询字符串但没有匹配的书籍时忘记这样做。您只需要在 .then 函数中添加 else 语句:
search_books = (val) => {
if (val.length !== 0 ) {
BooksAPI.search( val, 10 ).then((books) => {
if (books.length > 0 ) {
books = this.changeBookShelf(books)
this.setState(() => {
return {Books: books}
})
} else {
this.setState({Books: []})
}
})
} else {
this.setState({Books: [], query: ''})
}
推荐阅读
- c# - Mailkit 错误未指定 uid。参数名称:uids
- asp.net-mvc - 从 Azure 中托管的 MVC 应用程序发送电子邮件不起作用
- c# - 对通过 Startup 类调用另一个控制器的控制器进行单元测试
- swift - 订购 Firebase 数据库,然后使用 Xcode 迭代和更新项目
- npm - npm install --save web3@1.0.0-beta.36 在 Mac 上失败
- angular - Firebase 无法以 Angular 的形式存储图像
- php - PHP通过http请求读取csv文件
- android - RxJava 的 retryWhen 操作符
- maven - Maven项目中自动化框架组件的结构
- batch-file - 如何记录任务列表的计数