簡體   English   中英

如何從3個不同的React狀態中刪除該項目?

[英]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() {
    //...
  }
}

當前,嘗試刪除項目會從列表數組中刪除所有列表。

這是React開發工具的屏幕截圖,可讓您大致了解每種狀態。 React開發工具

如果我遺漏了任何重要信息,請告訴我。

我相信您需要在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM