简体   繁体   English

如何从3个不同的React状态中删除该项目?

[英]How can I remove this item from 3 different React states?

I'm making a to-do app that allows you to create multiple lists with their own to-do items. 我正在制作一个待办事项应用程序,可让您使用自己的待办事项创建多个列表。 On my main app component I have a state for all of the todos, all of the lists, and the current list. 在我的主要应用程序组件上,我具有所有待办事项,所有列表和当前列表的状态。 On deleting an item I need the item to be removed from all 3 states. 在删除项目时,我需要将该项目从所有3个状态中删除。 I can easily remove it from the array of all to-do items and the current list. 我可以轻松地将其从所有待办事项数组和当前列表中删除。 The trouble is removing it from the list in the lists array. 问题是从列表数组的列表中删除它。 Here is the component code that relates to this issue: 以下是与此问题相关的组件代码:

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

Currently, trying to delete an item removes all lists from the lists array. 当前,尝试删除项目会从列表数组中删除所有列表。

Here is a screenshot of the React dev tool to give you an idea of what each state looks like... 这是React开发工具的屏幕截图,可让您大致了解每种状态。 React开发工具

Please let me know if I left out any critical information. 如果我遗漏了任何重要信息,请告诉我。

I believe you need to use .map on the lists substate: 我相信您需要在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