Javascript 使用设置状态更新书架
我有初学者模板,我转换为反应网站学习,我不知道如何使用设置状态更新书架。在项目中,我有App.js文件,其中有changeself函数,我想使用setState函数来更新当前状态,而不是使用BooksAPI.update函数中的BooksAPI.getAll来完成相同的工作Javascript 使用设置状态更新书架,javascript,reactjs,Javascript,Reactjs,我有初学者模板,我转换为反应网站学习,我不知道如何使用设置状态更新书架。在项目中,我有App.js文件,其中有changeself函数,我想使用setState函数来更新当前状态,而不是使用BooksAPI.update函数中的BooksAPI.getAll来完成相同的工作 changeShelf(book, shelf) { BooksAPI.update(book, shelf).then(() => { BooksAPI.getAll().then((book
changeShelf(book, shelf) {
BooksAPI.update(book, shelf).then(() => {
BooksAPI.getAll().then((books) => {
this.collectBooks(books)
})
})
}
App.js文件:
BooksAPI.js文件:
首先,你必须从当前书架上取下这本书。然后把书放在右边的书架上 您可以将
changeelf
更改为以下内容:
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);
}
this.setState({books})
?在这个状态下,我没有书,而是使用currentlyReadingBooks,WantReadBooks&readBooks我也不能直接使用它,因为我有多本书,并且只对其中一本书进行了更改。如果我想添加它,我将重复很多代码,因为您编写的大部分内容都已经是collectBooks函数的一部分。请检查此处,我已更新了我的答案,changeself
现在可以重新使用collectBooks
。