簡體   English   中英

TypeError:無法在反應中將未定義或 null 轉換為 object

[英]TypeError: Cannot convert undefined or null to object in react

我正在嘗試使用以下代碼將一個簡單的 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: Cannot convert undefined or null to object。

這讓我很困惑,因為我嘗試使用Object.keys(books[0])從 output 數組中獲取密鑰並且它有效,鏈接到 JS Bin 有人可以幫我解決這個問題嗎?

因為在渲染時不會加載數據。 這將導致嘗試訪問books[0]

寫這樣的條件,

{books.length>0&&
 <tr>
        <th></th>
        {Object.keys(books[0]).map((item) => {
          return <th key={item}>{item}</th>;
        })}
      </tr>
}

從 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
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM