gpt4 book ai didi

javascript - React 使用 setState 更新书架

转载 作者:行者123 更新时间:2023-11-30 20:05:05 28 4
gpt4 key购买 nike

我有入门模板,我将其转换为 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

最佳答案

首先,您必须从当前书架上移除这本书。然后把书放到右边的书架上。

您可以将 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);
}

关于javascript - React 使用 setState 更新书架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53020392/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com