过滤数组onClick并呈现数组中的其余项目

时间:2018-08-13 13:06:23

标签: javascript arrays reactjs object

我已经创建了一个待办事项应用程序,并且我尝试在3种不同条件下(全部已完成,未完成)过滤待办事项。默认情况下,我想显示所有项目,然后过滤它们。我知道我可以使用过滤器,例如:

Long timestamp = System.getCurrentTimeInMillis()
SharedPreferences prefs = getApplicationContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
prefs.edit().putLong("time", timestamp).commit();

但是我不知道如何渲染所有这些,然后仅渲染过滤的项目。代码如下:

array.filter(t => t.completed) or array.filter(t => !t.completed)

2 个答案:

答案 0 :(得分:3)

您所描述的内容可以通过多种方式实现,但直接的答案是使用状态(如果通过父级控制过滤器,则使用props):

getFilteredNotes() {
  switch (this.state.noteFilter) {
    case 'completed':
      return this.state.notes.filter(n => n.completed);
    case 'incomplete'
      return this.state.notes.filter(n => !n.completed);
    case 'all':
    default:
      return this.state.notes;
}

render() {
  return this.getFilteredNotes().map(n => (
    <Todo note={n}/>
  ));
}

答案 1 :(得分:1)

只需使用map渲染过滤后的数组;

render() {
  return (
    <div>
       {this.state.todos.filter(t => t.completed).map(t => (
         <TodoItem>{t.text}</TodoItem>
        }
    </div>
  )
}