我试图让我的api显示数据,但它一直返回错误books.map is not a function
。我知道当页面加载时,我的数组是空的,但它可能需要(books || [])
,但这也不起作用。。有什么想法吗?
我只想能够将数据映射到表中,然后对其进行操作。当我控制台.log(books(时,我得到了我想要的数据,但映射不起作用。
我的代码:
import PropTypes from "prop-types";
import BookService from "../services/BookService";
import Books from "./Books";
import axios from "axios";
import { Table, Container } from "react-bootstrap";
const BooksList = () => {
const [books, setBooks] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [booksPerPage, setBooksPerPage] = useState(10);
useEffect(() => {
const fetchBooks = async () => {
const res = await axios.post("http://nyx.vima.ekt.gr:3000/api/books");
setBooks(res.data);
console.log(setBooks);
setLoading(false);
};
fetchBooks();
}, []);
console.log(books, "BooksList");
return (
<Container>
<div className="container mt-5">
<h1 className="text-primary mb-3"> Books </h1>
<Table striped bordered hover size="lg">
<thead>
<tr>
<th>#</th>
<th>Book Author</th>
<th>Book Pages</th>
<th>Book Publication City</th>
<th>Book Publication Country</th>
<th>Book Publication Year</th>
<th>Book Title</th>
</tr>
</thead>
{books.map(book => (
<tbody>
<tr>
<td>{book.id}</td>
<td>{book.book_pages}</td>
</tr>
</tbody>
))}
</Table>
</div>
</Container>
);
};
export default BooksList;
正如Jay所说,你应该执行setBooks(res.data.books)
,但我也建议你从API结果中控制错误,如果API关闭,前端应该知道如何管理错误,而不是崩溃。一种方法是检查res.data.books
的竞争是否是数组。
你的完整代码应该是这样的:
import PropTypes from "prop-types";
import BookService from "../services/BookService";
import Books from "./Books";
import axios from "axios";
import { Table, Container } from "react-bootstrap";
const BooksList = () => {
const [books, setBooks] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [booksPerPage, setBooksPerPage] = useState(10);
useEffect(() => {
const fetchBooks = async () => {
try {
setError(false);
setLoading(true);
const res = await axios.post("http://nyx.vima.ekt.gr:3000/api/books");
setBooks(res.data.books);
console.log(setBooks);
setLoading(false);
} catch(err) {
console.log(err);
setError(true);
setLoading(false);
setBooks([]);
}
};
fetchBooks();
}, []);
console.log(books, "BooksList");
if(error) return <div>Error message</div>
return (
<Container>
<div className="container mt-5">
<h1 className="text-primary mb-3"> Books </h1>
<Table striped bordered hover size="lg">
<thead>
<tr>
<th>#</th>
<th>Book Author</th>
<th>Book Pages</th>
<th>Book Publication City</th>
<th>Book Publication Country</th>
<th>Book Publication Year</th>
<th>Book Title</th>
</tr>
</thead>
{books.map(book => (
<tbody>
<tr>
<td>{book.id}</td>
<td>{book.book_pages}</td>
</tr>
</tbody>
))}
</Table>
</div>
</Container>
);
};
export default BooksList;
您必须这样设置数据,因为所有响应数据都在书籍属性中
setBooks(res.data.books);