我想通过对数组使用 map 函数将组件添加到 dom 中。
{books.map((book) => <Book/>)}
但是,它并没有添加任何东西,就好像books数组是空的?
我使用 {console.log(books)}
打印书籍它是非空的。这里有什么问题?我附上了渲染函数。
render() {
let books = this.state.books;
return (<div className="bookshelf">
<h2 className="bookshelf-title">{this.titles[this.props.shelf]}</h2>
<div className="bookshelf-books">
<ol className="books-grid">
{books.map((book) => <Book/>)}
</ol>
</div>
</div>)
}
对于任何人的信息,我通过 api 调用获取 book 的值。
componentWillMount() {
BooksAPI.getAll().then((books) => {
books.forEach((book) => {
if (this.state.shelf === book.shelf){
// console.log(book);
this.state.books.push(book);
}
})
})
}
谢谢你,如果你明白发生了什么。
最佳答案
错误在于您正在直接改变
状态并且它不会重新呈现,因此更改不会反射(reflect)在您的 DOM 中。使用setState
来更新状态
componentWillMount() {
BooksAPI.getAll().then((books) => {
const tempBooks = [];
books.forEach((book) => {
if (this.state.shelf === book.shelf){
// console.log(book);
tempBooks.push(book);
}
})
this.setState(prevState => ({books: [...prevState.books, ...tempBooks]}))
})
}
关于javascript - React - 在 Map 函数中添加组件不添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47427502/