【问题标题】:Make some filters on an array then unfilter with an "All" filter在数组上制作一些过滤器,然后使用“全部”过滤器取消过滤
【发布时间】:2018-06-20 12:47:19
【问题描述】:

我正在用 React 构建经典的“待办事项”应用程序。 我想实现基于状态过滤待办事项的功能:已完成、活动和全部。

我通常复制我的原始状态,然后将更改应用到副本。

问题是我在数组上使用过滤器时丢失了原始 TODO,所以当我使用“全部”按钮时,我无法在过滤之前检索我的数据。

这是我的状态:

  state = {
    todos: [
      { id: 432402, title: "Make some music", isDone: false },
      { id: 421402, title: "Conquer the world", isDone: false },
      { id: 427740, title: "Go to the mall", isDone: true },
      { id: 471402, title: "Do some homework", isDone: false }
    ]
  };

这是我用来根据完成状态过滤状态的功能之一

  filterCompletedTasks = () => {
    const todos = [...this.state.todos];
    const filtered = todos.filter(todo => {
      return todo.isDone;
  });

我目前不使用 redux 或 Immutable.js,所以任何关于使用简单 React 的帮助都会非常有用。

【问题讨论】:

  • 你在修改过滤后的状态,你是如何使用filterCompletedTasks的。需要更多代码才能提供帮助
  • 是的。我使用 this.setState({ todos: filtered });

标签: javascript arrays reactjs filtering state


【解决方案1】:

关键思想是保持所有项目在您的状态下不被修改。 我复制了你的例子。看看它。我在状态中添加了showDone 变量,为您的应用程序添加基本的过滤灵活性。当 showDone 等于 true 时,我在 state.todos 上应用 filter 方法并将结果分配给负责显示结果的 todosList 变量。

class App extends React.Component {
  
  state = {
    showDone: false,
    todos: [
      { id: 432402, title: "Make some music", isDone: false },
      { id: 421402, title: "Conquer the world", isDone: false },
      { id: 427740, title: "Go to the mall", isDone: true },
      { id: 471402, title: "Do some homework", isDone: false },
    ],
  }
  
  toggleFilter = () => this.setState({ showDone: !this.state.showDone })
  
  render() {
    let todosList = this.state.todos;
    
    if (this.state.showDone) {
      todosList = todosList.filter((todo) => todo.isDone);
    }
 
    return (
      <div>
        <h4>ToDo List</h4>
        <button onClick={this.toggleFilter}>Toggle show done</button>
         {todosList.map((todo, i) => (
          <div key={todo.id}>
            {todo.title}
            {todo.isDone && <span>[DONE]</span>}
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react">

【讨论】:

  • 我认为this.setState((oldState) =&gt; { return { showDone: !oldState.showDone}; }); 是实现这一目标的更好方法。
  • @inaumov17:谢谢!您的解决方案正是我想知道的。回顾一下:我没有过滤原始数组然后将状态设置为过滤后的数组,而是根据条件语句呈现一个新的过滤列表。
  • @FrancescoDiBlasi 你明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 2017-10-19
相关资源
最近更新 更多