试图将对象数组映射为组件,在组件内部,但其中的 console.log 永远不会像 JSX 那样记录日志?我是 Gatsby 的新手并试图更好地理解它,我的代码如下。它不再在加载时产生任何错误;以前的错误主要是“.map 不是函数”,因为它在调用之前没有生成 objs 数组。然而,再次加载时没有错误,只是没有渲染组件。
非常感谢任何帮助或建议,谢谢。
const IndexPage = () => {
var bookObjHolderArray = [];
// * Initialize book collection
const [books, setBooks] = useState(() => {
GetInfo().then((querySnapshot) =>{
querySnapshot.forEach((doc) => {
let bookObjHolderTemp = {
title: doc.data().title,
author: doc.data().author,
yearPublished: doc.data().yearPublished,
pageCount: doc.data().pageCount,
genre: doc.data().genre,
id: Math.random() * 1000
};
bookObjHolderArray.push(bookObjHolderTemp);
});
});
return bookObjHolderArray;
});
return(<>
<div className="header">
<span>Let's find a new book to read</span>
<Modal/>
</div>
<span className="section btn-container">
<button className="submit-btn" type='submit' onClick={inputHandler}>Let's read!</button>
<button className="clear-btn" type="submit">Clear Filters</button>
</span>
<BookContainer books={books}/>
</>);
}
export default IndexPage;
const BookContainer = ({books}) => {
console.log(books);
return(<>
<div id="display" className="section">
<input id='search-input' className="search-input"
type="search" placeholder="Search book by title..."></input>
<div className="section book-collection">
{books.map((book) => {
console.log(book);
<Book key={books.id} title={book.title} author={books.author} yearPublished={books.yearPublished} pageCount={books.pageCount} genre={books.genre}/>
})}
</div>
</div>
</>);
}
export default BookContainer;
import React from "react";
import cover from "../images/fairyTale.jpg";
import "../styles/book.scss";
const Book = (props) => {
console.log(props.title);
return(<div className="book-container">
<img src={cover} className="book-cover" alt="Cover"/>
<span className="book-title">{props.title}</span>
<div className="book-filter-container">
<span className="book-filter">{props.genre}</span>
<span className="book-filter">{props.yearPublished}</span>
<span className="book-filter">{props.pageCount} p.</span>
</div>
</div>);
}
export default Book;