我有一个入门模板,我将该模板转换到React网站进行学习,但我不知道如何使用setState更新书架。在项目中,我有App.js文件,其中有changeShelf函数,我想使用setState函数更新当前状态,而不是在BooksAPI.update函数中使用BooksAPI.getAll来完成相同的工作。
changeShelf(book, shelf) {
BooksAPI.update(book, shelf).then(() => {
BooksAPI.getAll().then((books) => {
this.collectBooks(books)
})
})
}
App.js文件: https://codeshare.io/5wK36x
BooksAPI.js文件: https://codeshare.io/adDo9g
答案 0 :(得分:1)
首先,您必须将书从当前书架中取出。然后将书添加到正确的书架上。
您可以将changeShelf
更改为以下内容:
getShelfWithoutBook(shelf, book) {
return shelf.filter(item => item !== book);
}
changeShelf(book, shelf) {
this.setState({
currentlyReadingBooks: this.getShelfWithoutBook(this.state.currentlyReadingBooks, book),
wantToReadBooks: this.getShelfWithoutBook(this.state.wantToReadBooks, book),
readBooks: this.getShelfWithoutBook(this.state.readBooks, book)
});
if (shelf === 'currentlyReading') {
this.setState({
currentlyReadingBooks: this.state.currentlyReadingBooks.push(book)
});
} else if (currentShelf === 'wantToRead') {
this.setState({
wantToReadBooks: this.state.wantToReadBooks.push(book)
});
} else if (currentShelf === 'read') {
this.setState({
readBooks: this.state.readBooks.push(book)
});
}
}
这可以写得不太重复,但是我希望这样更容易理解。
编辑:或者您可以重复使用collectBooks
方法:
changeShelf(book, shelf) {
// collect all books in one list:
const books = [
...this.state.currentlyReadingBooks,
...this.state.wantToReadBooks,
...this.state.readBooks
];
// remove the book you want to change:
const booksWithoutThisBook = books.filter(item => item !== book);
// update the shelf of the current book:
book.shelf = shelf;
// re-add the changed book:
const booksWithUpdatedBook = [...booksWithoutThisBook, book];
// re-run the collectBooks method:
this.collectBooks(booksWithUpdatedBook);
}