我正在尝试管理我的本地州,同时也更新了一个包含书籍列表的API。在此设置中,当updateShelf方法收到书籍和书架时,它会检查书籍是否已经处于书籍状态,如果不是,则应将书籍状态的书籍参数联系起来。苦苦思索如何做到这一点。
class BooksApp extends React.Component {
state = {
books: []
};
componentDidMount() {
console.log("MOUNTING");
BooksAPI.getAll().then(books => {
this.setState({ books });
});
}
selectStateUpdate = (book, shelf) => {
this.updateShelf(book, shelf);
};
updateShelf = (book, shelf) => {
BooksAPI.update(book, shelf).then(() => {
let bookscopy = { ...this.state.books };
console.log(bookscopy);
for (let i = 0; this.state.books.length > i; i++) {
if (this.state.books[i].title === book.title) {
bookscopy[i].shelf = shelf;
this.setState({ bookscopy });
} else
this.setState({
books: bookscopy.concat(book)
});
}
});
};
}
参考项目> here
答案 0 :(得分:0)
您可以使用setState
功能,并按照这样做
updateShelf = (book, shelf) => {
BooksAPI.update(book, shelf)
.then(() => {
this.setState(prevState => {
const updatedBook = prevState.books
.filter(b => b.title === book.title)
.map(_book => ({
..._book,
shelf
}))
return {
books: [
...prevState.books.filter(b => b.title !== book.title),
updatedBook
]
}
})
})
}
它做什么?
答案 1 :(得分:0)
您尝试在每次循环迭代时更新状态:
public_html
尝试这样的事情:
for (let i=0; this.state.books.length > i; i++) {
if (this.state.books[i].title === book.title) {
bookscopy[i].shelf = shelf;
this.setState({bookscopy})
} else
this.setState({
books: bookscopy.concat(book)
})
}
})