我正在用 React-Redux 建立一个书店。代码编译成功,但我在浏览器中显示以下内容。
BookList
src/containers/BookList.js:42
39 | <th>Category</th>
40 | </tr>
41 | </thead>
> 42 | <tbody>
| ^ 43 | {bookFilter.map((book) => <Book key={book.id} book={book} remove={removeHandler} />)}
44 | </tbody>
45 | </table>
我的组件: 类别过滤器组件
import React from 'react';
import PropTypes from 'prop-types';
const CategoryFilter = ({ handleFilterChange, categories }) => (
<select onChange={handleFilterChange}>
<option value="all">All</option>
{categories.map((category) => {
<option key={category}>{category}</option>;
})}
</select>
);
CategoryFilter.propTypes = {
handleFilterChange: PropTypes.func,
categories: PropTypes.arrayOf(PropTypes.string),
};
CategoryFilter.defaultProps = {
handleFilterChange: null,
categories: [],
};
export default CategoryFilter;
BookList 组件
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import PropTypes from 'prop-types';
import Book from '../components/Book';
import { removeBook, changeFilter } from '../actions/index';
import CategoryFilter from '../components/CategoryFilter';
const BookList = ({ categories }) => {
const books = useSelector((state) => state.books);
const filter = useSelector((state) => state.filter);
const dispatch = useDispatch();
const removeHandler = (e) => {
const id = parseFloat(e.target.value);
dispatch(removeBook(id));
};
const handleFilterChange = (e) => {
dispatch(changeFilter(e.target.value));
};
const bookFilter = () => {
if (filter !== 'all') {
return books.filter((book) => book.category === filter);
}
return books;
};
return (
<div>
<CategoryFilter categories={categories} handleFilterChange={handleFilterChange} />
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Category</th>
</tr>
</thead>
<tbody>
{bookFilter.map((book) => <Book key={book.id} book={book} remove={removeHandler} />)}
</tbody>
</table>
</div>
);
};
BookList.propTypes = {
categories: PropTypes.arrayOf(PropTypes.string),
};
BookList.defaultProps = {
categories: [],
};
export default BookList;
我不明白为什么会抛出浏览器错误,说 TypeError: bookFilter.map is not a function
我正在用 React-Redux 建立一个书店。代码编译成功,但我在浏览器中显示以下内容。