[英]How can I remove this item from 3 different React states?
我正在制作一個待辦事項應用程序,可讓您使用自己的待辦事項創建多個列表。 在我的主要應用程序組件上,我具有所有待辦事項,所有列表和當前列表的狀態。 在刪除項目時,我需要將該項目從所有3個狀態中刪除。 我可以輕松地將其從所有待辦事項數組和當前列表中刪除。 問題是從列表數組的列表中刪除它。 以下是與此問題相關的組件代碼:
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: [],
lists: [],
currentList: ''
};
this.deleteItem = this.deleteItem.bind(this);
//...
}
//...
deleteItem(itemId) {
this.setState(prevState => ({
todos: prevState.todos.filter(item => itemId !== item.id),
lists: prevState.lists.find(list => list.id === this.state.currentList.id).todos.filter(item => itemId !== item.id),
currentList: prevState.currentList.todos.filter(item => itemId !== item.id)
}));
}
render() {
//...
}
}
當前,嘗試刪除項目會從列表數組中刪除所有列表。
如果我遺漏了任何重要信息,請告訴我。
我相信您需要在lists
子狀態上使用.map
:
lists: prevState.lists.map(list => ({
...list, // or "id: list.id, text: list.text," if you are not ok with spread operator
todos: list.todos.filter(item => itemId !== item.id)
}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.