我一直困惑为什么删除和状态更新后项目-card
不会从DOM中消失。我的编辑功能运行良好,并且我的代码中出现拼写错误和错误的变量等。
这是我的App(顶部组件)状态对象:
state = {
decks: [],
cards: [],
selectedCards: [],
selectedDecks: [],
currentUser: null,
users: []
}
我在App中的删除功能(乐观),该功能向下传递到deckLayout
组件:
deleteCard = (cardId, deckId) => {
const cardCopy = this.state.cards.slice()
const foundOldCardIdx = cardCopy.findIndex(card => card.id === cardId)
cardCopy.splice(foundOldCardIdx, 1)
this.setState({
cards: cardCopy
}, console.log(this.state.cards, cardCopy))
this.filterCards(deckId)
console.log(this.state.cards)
fetch(`http://localhost:9000/api/v1/cards/${cardId}`, {
method: 'DELETE'
})
};
这是一个filterCards
函数,在删除和状态更新后才调用(这对于“编辑”有效):
filterCards = (deckId) => {
if (this.state.cards.length === 0) {
alert('No cards yet!')
} else {
const filteredCards = this.state.cards.filter(card => card.deck_id === deckId)
this.setState({
selectedCards: filteredCards
})
this.filterDecks()
}
};
然后调用filterDecks
函数:
filterDecks = () => {
if (this.state.currentUser) {
const filteredDecks = this.state.decks.filter(deck => {
return deck.user_id === this.state.currentUser.id
})
this.setState({
selectedDecks: filteredDecks
})
} else {
alert('Login or sign up')
}
};