TypeError:无法在 React 中将未定义或空转换为对象
2021-05-04
22835
我尝试使用以下代码将一个简单的 HTML 表呈现到屏幕上:
import { useEffect, useState } from "react";
import "./App.css";
import { getAllBooks } from "./services/bookService";
function App() {
const [books, setBooks] = useState([]);
useEffect(() => {
const loadBooks = async () => {
try {
const response = await getAllBooks();
console.log(response.data.books);
setBooks(response.data.books);
} catch (error) {
console.log(error);
}
};
loadBooks();
}, []);
return (
<div className="container">
<h1>Simple Inventory Table</h1>
<table>
<thead>
<tr>
<th></th>
{Object.keys(books[0]).map((item) => {
return <th key={item}>{item}</th>;
})}
</tr>
</thead>
</table>
</div>
);
}
export default App;
我获得的书籍数组如下所示:
const books = [
{
id: 1,
Title: "Book One",
Stock: 4,
ISBN: "9874223457654",
ImageURL: null,
Pages: 281,
createdAt: "2021-04-30T12:57:52.000Z",
updatedAt: "2021-04-30T13:43:07.000Z",
AuthorId: 1,
GenreId: 2
},
{
id: 2,
Title: "Book Two",
Stock: 5,
ISBN: "9825324716432",
ImageURL: null,
Pages: 231,
createdAt: "2021-04-30T12:57:52.000Z",
updatedAt: "2021-04-30T12:57:52.000Z",
AuthorId: 3,
GenreId: 6
}
];
但是,我得到的不是一行一列,而是错误:TypeError:无法将未定义或 null 转换为对象。
这让我很困惑,因为我曾尝试使用
Object.keys(books[0])
从输出数组中获取键,并且成功了,
Link to JS Bin
。有人可以帮我解决这个问题吗?
2个回答
因为数据在渲染时不会加载。这将导致在尝试访问
books[0]
时出现异常。
编写这样的条件,
{books.length>0&&
<tr>
<th></th>
{Object.keys(books[0]).map((item) => {
return <th key={item}>{item}</th>;
})}
</tr>
}
Anoop Joshi P
2021-05-04
从 booksService.js 导出 books 数组以显示所有键
import { useEffect, useState } from "react";
import { getAllBooks } from "./bookService";
function App() {
const [books, setBooks] = useState([]);
useEffect(() => {
const loadBooks = async () => {
try {
const response = await getAllBooks();
console.log(response);
setBooks(response);
} catch (error) {
console.log(error);
}
};
loadBooks();
}, []);
return (
<div className="container">
<h1>Simple Inventory Table</h1>
<table>
<thead>
{books.length > 0 && (
<tr>
<th></th>
{Object.keys(books[0]).map((item) => {
return <th key={item}>{item}</th>;
})}
</tr>
)}
</thead>
</table>
</div>
);
}
export default App;
bookService.js 如下所示:
const books = [
{
id: 1,
Title: "Book One",
Stock: 4,
ISBN: "9874223457654",
ImageURL: null,
Pages: 281,
createdAt: "2021-04-30T12:57:52.000Z",
updatedAt: "2021-04-30T13:43:07.000Z",
AuthorId: 1,
GenreId: 2
},
{
id: 2,
Title: "Book Two",
Stock: 5,
ISBN: "9825324716432",
ImageURL: null,
Pages: 231,
createdAt: "2021-04-30T12:57:52.000Z",
updatedAt: "2021-04-30T12:57:52.000Z",
AuthorId: 3,
GenreId: 6
}
];
async function getAllBooks() {
return books;
}
module.exports = {
getAllBooks
};
snehal gugale
2021-05-04