我已经在我的react应用中实现了搜索过滤器,在我选择标签以更改搜索过滤器条件之前,一切正常。
class BookList extends Component {
state = {
search: '',
selectedValue: 'name',
options: [
{
name: 'Name',
value: 'name',
},
{
name: 'Author',
value: 'author',
},
{
name: 'ISBN',
value: 'isbn',
}
]
}
updateSearch (e) {
this.setState({search: e.target.value});
}
selectedValueHandler (e) {
this.setState({selectedValue: e.target.value});
}
render () {
if (this.state.selectedValue === 'name') {
let filteredBooks = this.props.books.filter(book => {
return book.name.toLowerCase().indexOf(this.state.search) !== -1;
})
} else if (this.state.selectedValue === 'author') {
let filteredBooks = this.props.books.filter(book => {
return book.author.toLowerCase().indexOf(this.state.search) !==
-1;
})
} else if (this.state.selectedValue === 'isbn') {
let filteredBooks = this.props.books.filter(book => {
return book.isbn.indexOf(this.state.search) !== -1;
})
}
return (
<div>
<div className='SearchInput'>
<input type='text'
value={this.state.search}
onChange={this.updateSearch.bind(this)} />
<select
id="searchSelect"
name="searchSelect"
onChange={this.selectedValueHandler.bind(this)} >
{this.state.options.map(item => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
</div>
<div className='BookList'>
<ul>
{filteredBooks.map(book => {
return <Book key={book.book_id} name={book.name} author={book.author} isbn={book.isbn} />
})}
</ul>
</div>
</div>
)
}
};
export default BookList;
当我实现此代码时,我得到了错误:69行:'filteredBooks'未定义为no-undef。
试图放置this.state.selectedValue而不是name,但是它也不起作用。
任何想法如何解决问题?
答案 0 :(得分:2)
let
变量在本地范围内是最近的环绕花括号。在if语句上方定义变量。
render () {
let filteredBooks;
if (this.state.selectedValue === 'name') {
filteredBooks = this.props.books.filter(book => {
return book.name.toLowerCase().indexOf(this.state.search) !== -1;
})
...
不相关,这是缩短代码的一种方法:
const { books } = this.props;
const { search } = this.state;
const filteredBooks = books.filter(book =>
book[search].toLowerCase().includes(search)
)