Filtering Todo list in React Js(在 React Js 中过滤 Todo 列表)
问题描述
我是 React 新手(我习惯于使用 Angular),我目前正在根据类别选择过滤我的 Todo 列表应用程序.
我从 http://todomvc.com/examples/react/#/克隆了 Todo 列表应用 .我添加了一个类别"输入,该输入有效,但现在我尝试在显示列表后按类别进行过滤.
我目前没有任何类别搜索功能,我正在寻找一些关于从哪里开始的指导.我将在下面发布代码,但如果你想克隆它,这里是我的仓库的链接:https://github.com/aenser/todo-react
app.jsx
var app = app ||{};(功能 () {'使用严格';app.ALL_TODOS = '全部';app.ACTIVE_TODOS = '活跃';app.COMPLETED_TODOS = '完成';var TodoFooter = app.TodoFooter;var TodoItem = app.TodoItem;var ENTER_KEY = 13;var TodoApp = React.createClass({获取初始状态:函数(){返回 {现在显示:app.ALL_TODOS,空,newTodo: '',新类别:''};},组件DidMount:函数(){var setState = this.setState;var路由器=路由器({'/': setState.bind(this, {nowShowing: app.ALL_TODOS}),'/active': setState.bind(this, {nowShowing: app.ACTIVE_TODOS}),'/completed': setState.bind(this, {nowShowing: app.COMPLETED_TODOS})});router.init('/');},handleChange:函数(事件){this.setState({newTodo: event.target.value});},handleCategoryChange:函数(事件){this.setState({newCategory: event.target.value});},handleNewTodoKeyDown:函数(事件){if (event.keyCode !== ENTER_KEY) {返回;}event.preventDefault();var val = this.state.newTodo.trim();var cat = this.state.newCategory.trim();如果(瓦尔,猫){this.props.model.addTodo(val, cat);this.setState({newTodo: '', newCategory: ''});}},toggleAll:功能(事件){var 已检查 = event.target.checked;this.props.model.toggleAll(选中);},切换:功能(todoToToggle){this.props.model.toggle(todoToToggle);},销毁:函数(待办事项){this.props.model.destroy(todo);},功能(待办事项){this.setState({editing: todo.id});},保存:函数(todoToSave,文本,猫){this.props.model.save(todoToSave, text, cat);this.setState({editing: null});},取消:函数(){this.setState({editing: null});},清除完成:函数(){this.props.model.clearCompleted();},渲染:函数(){变量页脚;变量主;var todos = this.props.model.todos;var shownTodos = todos.filter(function (todo) {开关(this.state.nowShowing){案例 app.ACTIVE_TODOS:返回 !todo.completed;案例 app.COMPLETED_TODOS:返回 todo.completed;默认:返回真;}}, 这);var todoItems = shownTodos.map(function (todo) {返回 (<待办事项键={todo.id}待办事项={待办事项}onToggle={this.toggle.bind(this, todo)}onDestroy={this.destroy.bind(this, todo)}onEdit={this.edit.bind(this, todo)}编辑={this.state.editing === todo.id}onSave={this.save.bind(this, todo)}onCancel={this.cancel}/>);}, 这);var activeTodoCount = todos.reduce(function (accum, todo) {返回 todo.completed ?累加:累加+1;}, 0);var completedCount = todos.length - activeTodoCount;if (activeTodoCount || completedCount) {页脚 =<待办事项页脚计数={activeTodoCount}完成计数={完成计数}nowShowing={this.state.nowShowing}onClearCompleted={this.clearCompleted}/>;}如果(todos.length){主要 = (<section className="main"><输入className="toggle-all"类型=复选框"onChange={this.toggleAll}检查={activeTodoCount === 0}/><ul className="待办事项列表">{待办事项}</ul></部分>);}返回 (<标题类名=标题"><h1>待办事项</h1><form onKeyDown={this.handleNewTodoKeyDown}><输入placeholder="需要做什么?"价值={this.state.newTodo}自动对焦={真}className="new-todo"onChange={this.handleChange}/><选择值={this.state.newCategory} className="new-todo"onChange={this.handleCategoryChange}><option value="">选择一个类别</option><option value="紧急">紧急</option><option value="Soon">很快</option><option value="Anytime">Anytime</option></选择></表格></标题>{主要的}{页脚}</div>);}});var model = new app.TodoModel('react-todos');函数渲染(){反应.渲染(<TodoApp 模型={model}/>,document.getElementsByClassName('todoapp')[0]);}模型.订阅(渲染);使成为();})();todoModel.js
var app = app ||{};(功能 () {'使用严格';var Utils = app.Utils;//通用模型"对象.你可以使用任何东西//你想要的框架.对于这个应用程序//甚至可能不值得分离这个逻辑//out,但我们这样做是为了演示一种方法//分离出应用程序的各个部分.app.TodoModel = 功能(键){this.key = 键;this.todos = Utils.store(key);this.onChanges = [];};app.TodoModel.prototype.subscribe = function (onChange) {this.onChanges.push(onChange);};app.TodoModel.prototype.inform = function () {Utils.store(this.key, this.todos);this.onChanges.forEach(function (cb) { cb(); });};app.TodoModel.prototype.addTodo = 功能(标题,类别){this.todos = this.todos.concat({id: Utils.uuid(),标题:标题,类别:类别,完成:假});this.inform();};app.TodoModel.prototype.toggleAll = 功能(选中){//注意:通常最好使用不可变数据结构,因为它们是//更容易推理并且 React 与它们配合得很好.这就是为什么//我们在任何地方都使用 map() 和 filter() 而不是改变数组或//待办事项本身.this.todos = this.todos.map(function (todo) {return Utils.extend({}, todo, {completed: checked});});this.inform();};app.TodoModel.prototype.filterAll = function () {this.todos = this.todos.map(function (todo) {返回 Utils.extend({}, todo);});this.inform();};app.TodoModel.prototype.toggle = 函数 (todoToToggle) {this.todos = this.todos.map(function (todo) {返回 todo !== todoToToggle ?去做 :Utils.extend({}, todo, {completed: !todo.completed});});this.inform();};app.TodoModel.prototype.destroy = function (todo) {this.todos = this.todos.filter(function (candidate) {返回候选人!==待办事项;});this.inform();};app.TodoModel.prototype.save = function (todoToSave, text, cat) {this.todos = this.todos.map(function (todo) {返回 todo !== todoToSave ?todo : Utils.extend({}, todo, {title: text}, {category: cat});});this.inform();};app.TodoModel.prototype.clearCompleted = function () {this.todos = this.todos.filter(function (todo) {返回 !todo.completed;});this.inform();};})();
todoItem.jsx
var app = app ||{};(功能 () {'使用严格';var ESCAPE_KEY = 27;var ENTER_KEY = 13;app.TodoItem = React.createClass({处理提交:函数(事件){var val = this.state.editText.trim();var cat = this.state.editCategoryText.trim();如果(瓦尔||猫){this.props.onSave(val, cat);this.setState({editText: this.props.todo.title, editCategoryText: this.props.todo.category});} 别的 {this.props.onDestroy();}},句柄函数(事件){this.props.onEdit();this.setState({editText: this.props.todo.title, editCategoryText: this.props.todo.category});},handleKeyDown:函数(事件){if (event.which === ESCAPE_KEY) {this.setState({editText: this.props.todo.title});this.props.onCancel(event);} else if (event.which === ENTER_KEY) {this.handleSubmit(事件);}},handleChange:函数(事件){如果(this.props.editing){this.setState({editText: event.target.value});}},handleCategoryChange:函数(事件){如果(this.props.editing){this.setState({editCategoryText: event.target.value});}},获取初始状态:函数(){返回{editText:this.props.todo.title,editCategoryText:this.props.todo.category};},/*** 这是一个完全可选的性能增强,您可以* 在任何 React 组件上实现.如果您要删除此方法* 该应用程序仍然可以正常工作(并且仍然非常高效!),我们* 仅将其用作获取订单所需的代码量的示例* 数量级的性能改进.*/shouldComponentUpdate: 函数 (nextProps, nextState) {返回 (nextProps.todo !== this.props.todo ||nextProps.editing !== this.props.editing ||nextState.editText !== this.state.editText ||nextState.editCategoryText !== this.state.editCategoryText);},/*** 调用时更新状态后安全操作DOM* 上面 `handleEdit` 方法中的 `this.props.onEdit()`.* 有关更多信息,请参阅 https://facebook.github.io/react/docs/component-api.html#setstate 上的注释* 和 https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate*/componentDidUpdate: 函数 (prevProps) {if (!prevProps.editing && this.props.editing) {var node = React.findDOMNode(this.refs.editField);node.focus();node.setSelectionRange(node.value.length, node.value.length);}},渲染:函数(){返回 (
感谢您花时间帮助我弄清楚如何根据类别选择过滤我的搜索.
解决方案 您的界面有点混乱,因为您似乎使用相同的输入选择来为待办事项分配类别和过滤,我将在最后讨论答案,但现在,我只是使用类别选择器来输入数据和按类别过滤.
您的问题的答案非常简单.您只需按类别和已完成状态进行过滤.像这样:
var shownTodos = todos.filter(function(todo) {返回(todo.category === this.state.newCategory);}, this).filter(function (todo) {开关(this.state.nowShowing){案例 app.ACTIVE_TODOS:返回 !todo.completed;案例 app.COMPLETED_TODOS:返回 todo.completed;默认:返回真;}}, 这);
我会在底部为当前显示的分类添加更多按钮.您还可以为 nowShowingCategory
等类别添加一组新状态,例如 nowShowing
.按钮会将其设置为类别的 3 个值,您将在上述过滤器中使用该变量,而不是我示例中的 newCategory
.
I am new to React (I'm used to working with Angular) and I am currently working on filtering my Todo list app based on a category selection.
I cloned the Todo list app from http://todomvc.com/examples/react/#/ . I added a 'category' input, which works, but now I am trying to filter by category once the list is shown.
I currently don't have any search function for categories and am looking for some guidance as to where to start. I'll post the code below but here is the link to my repo if you want to clone it: https://github.com/aenser/todo-react
app.jsx
var app = app || {};
(function () {
'use strict';
app.ALL_TODOS = 'all';
app.ACTIVE_TODOS = 'active';
app.COMPLETED_TODOS = 'completed';
var TodoFooter = app.TodoFooter;
var TodoItem = app.TodoItem;
var ENTER_KEY = 13;
var TodoApp = React.createClass({
getInitialState: function () {
return {
nowShowing: app.ALL_TODOS,
editing: null,
newTodo: '',
newCategory: ''
};
},
componentDidMount: function () {
var setState = this.setState;
var router = Router({
'/': setState.bind(this, {nowShowing: app.ALL_TODOS}),
'/active': setState.bind(this, {nowShowing: app.ACTIVE_TODOS}),
'/completed': setState.bind(this, {nowShowing: app.COMPLETED_TODOS})
});
router.init('/');
},
handleChange: function (event) {
this.setState({newTodo: event.target.value});
},
handleCategoryChange: function (event) {
this.setState({newCategory: event.target.value});
},
handleNewTodoKeyDown: function (event) {
if (event.keyCode !== ENTER_KEY) {
return;
}
event.preventDefault();
var val = this.state.newTodo.trim();
var cat = this.state.newCategory.trim();
if (val, cat) {
this.props.model.addTodo(val, cat);
this.setState({newTodo: '', newCategory: ''});
}
},
toggleAll: function (event) {
var checked = event.target.checked;
this.props.model.toggleAll(checked);
},
toggle: function (todoToToggle) {
this.props.model.toggle(todoToToggle);
},
destroy: function (todo) {
this.props.model.destroy(todo);
},
edit: function (todo) {
this.setState({editing: todo.id});
},
save: function (todoToSave, text, cat) {
this.props.model.save(todoToSave, text, cat);
this.setState({editing: null});
},
cancel: function () {
this.setState({editing: null});
},
clearCompleted: function () {
this.props.model.clearCompleted();
},
render: function () {
var footer;
var main;
var todos = this.props.model.todos;
var shownTodos = todos.filter(function (todo) {
switch (this.state.nowShowing) {
case app.ACTIVE_TODOS:
return !todo.completed;
case app.COMPLETED_TODOS:
return todo.completed;
default:
return true;
}
}, this);
var todoItems = shownTodos.map(function (todo) {
return (
<TodoItem
key={todo.id}
todo={todo}
onToggle={this.toggle.bind(this, todo)}
onDestroy={this.destroy.bind(this, todo)}
onEdit={this.edit.bind(this, todo)}
editing={this.state.editing === todo.id}
onSave={this.save.bind(this, todo)}
onCancel={this.cancel}
/>
);
}, this);
var activeTodoCount = todos.reduce(function (accum, todo) {
return todo.completed ? accum : accum + 1;
}, 0);
var completedCount = todos.length - activeTodoCount;
if (activeTodoCount || completedCount) {
footer =
<TodoFooter
count={activeTodoCount}
completedCount={completedCount}
nowShowing={this.state.nowShowing}
onClearCompleted={this.clearCompleted}
/>;
}
if (todos.length) {
main = (
<section className="main">
<input
className="toggle-all"
type="checkbox"
onChange={this.toggleAll}
checked={activeTodoCount === 0}
/>
<ul className="todo-list">
{todoItems}
</ul>
</section>
);
}
return (
<div>
<header className="header">
<h1>todos</h1>
<form onKeyDown={this.handleNewTodoKeyDown}>
<input
placeholder="What needs to be done?"
value={this.state.newTodo}
autoFocus={true}
className="new-todo"
onChange={this.handleChange}
/>
<select value={this.state.newCategory} className="new-todo"
onChange={this.handleCategoryChange}>
<option value="">Select a Category</option>
<option value="Urgent">Urgent</option>
<option value="Soon">Soon</option>
<option value="Anytime">Anytime</option>
</select>
</form>
</header>
{main}
{footer}
</div>
);
}
});
var model = new app.TodoModel('react-todos');
function render() {
React.render(
<TodoApp model={model}/>,
document.getElementsByClassName('todoapp')[0]
);
}
model.subscribe(render);
render();
})();
todoModel.js
var app = app || {};
(function () {
'use strict';
var Utils = app.Utils;
// Generic "model" object. You can use whatever
// framework you want. For this application it
// may not even be worth separating this logic
// out, but we do this to demonstrate one way to
// separate out parts of your application.
app.TodoModel = function (key) {
this.key = key;
this.todos = Utils.store(key);
this.onChanges = [];
};
app.TodoModel.prototype.subscribe = function (onChange) {
this.onChanges.push(onChange);
};
app.TodoModel.prototype.inform = function () {
Utils.store(this.key, this.todos);
this.onChanges.forEach(function (cb) { cb(); });
};
app.TodoModel.prototype.addTodo = function (title, category) {
this.todos = this.todos.concat({
id: Utils.uuid(),
title: title,
category: category,
completed: false
});
this.inform();
};
app.TodoModel.prototype.toggleAll = function (checked) {
// Note: it's usually better to use immutable data structures since they're
// easier to reason about and React works very well with them. That's why
// we use map() and filter() everywhere instead of mutating the array or
// todo items themselves.
this.todos = this.todos.map(function (todo) {
return Utils.extend({}, todo, {completed: checked});
});
this.inform();
};
app.TodoModel.prototype.filterAll = function () {
this.todos = this.todos.map(function (todo) {
return Utils.extend({}, todo);
});
this.inform();
};
app.TodoModel.prototype.toggle = function (todoToToggle) {
this.todos = this.todos.map(function (todo) {
return todo !== todoToToggle ?
todo :
Utils.extend({}, todo, {completed: !todo.completed});
});
this.inform();
};
app.TodoModel.prototype.destroy = function (todo) {
this.todos = this.todos.filter(function (candidate) {
return candidate !== todo;
});
this.inform();
};
app.TodoModel.prototype.save = function (todoToSave, text, cat) {
this.todos = this.todos.map(function (todo) {
return todo !== todoToSave ? todo : Utils.extend({}, todo, {title: text}, {category: cat});
});
this.inform();
};
app.TodoModel.prototype.clearCompleted = function () {
this.todos = this.todos.filter(function (todo) {
return !todo.completed;
});
this.inform();
};
})();
todoItem.jsx
var app = app || {};
(function () {
'use strict';
var ESCAPE_KEY = 27;
var ENTER_KEY = 13;
app.TodoItem = React.createClass({
handleSubmit: function (event) {
var val = this.state.editText.trim();
var cat = this.state.editCategoryText.trim();
if (val || cat) {
this.props.onSave(val, cat);
this.setState({editText: this.props.todo.title, editCategoryText: this.props.todo.category});
} else {
this.props.onDestroy();
}
},
handleEdit: function (event) {
this.props.onEdit();
this.setState({editText: this.props.todo.title, editCategoryText: this.props.todo.category});
},
handleKeyDown: function (event) {
if (event.which === ESCAPE_KEY) {
this.setState({editText: this.props.todo.title});
this.props.onCancel(event);
} else if (event.which === ENTER_KEY) {
this.handleSubmit(event);
}
},
handleChange: function (event) {
if (this.props.editing) {
this.setState({editText: event.target.value});
}
},
handleCategoryChange: function (event) {
if (this.props.editing) {
this.setState({editCategoryText: event.target.value});
}
},
getInitialState: function () {
return {editText: this.props.todo.title, editCategoryText: this.props.todo.category};
},
/**
* This is a completely optional performance enhancement that you can
* implement on any React component. If you were to delete this method
* the app would still work correctly (and still be very performant!), we
* just use it as an example of how little code it takes to get an order
* of magnitude performance improvement.
*/
shouldComponentUpdate: function (nextProps, nextState) {
return (
nextProps.todo !== this.props.todo ||
nextProps.editing !== this.props.editing ||
nextState.editText !== this.state.editText ||
nextState.editCategoryText !== this.state.editCategoryText
);
},
/**
* Safely manipulate the DOM after updating the state when invoking
* `this.props.onEdit()` in the `handleEdit` method above.
* For more info refer to notes at https://facebook.github.io/react/docs/component-api.html#setstate
* and https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate
*/
componentDidUpdate: function (prevProps) {
if (!prevProps.editing && this.props.editing) {
var node = React.findDOMNode(this.refs.editField);
node.focus();
node.setSelectionRange(node.value.length, node.value.length);
}
},
render: function () {
return (
<li className={classNames({
completed: this.props.todo.completed,
editing: this.props.editing
})}>
<div className="view">
<input
className="toggle"
type="checkbox"
checked={this.props.todo.completed}
onChange={this.props.onToggle}
/>
<label onDoubleClick={this.handleEdit}>
{this.props.todo.title}
</label>
<label onDoubleClick={this.handleEdit}>
{this.props.todo.category}
</label>
<button className="destroy" onClick={this.props.onDestroy} />
</div>
<input
ref="editField"
value={this.state.editText}
className="edit"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
/>
<select value={this.state.EditCategoryText} className="edit" onChange={this.handleCategoryChange} defaultValue={this.props.todo.category} onKeyDown={this.handleKeyDown}>
<option value="Urgent">Urgent</option>
<option value="Soon">Soon</option>
<option value="Anytime">Anytime</option>
</select>
</li>
);
}
});
})();
Thank You for taking the time to help me figure out how to filter my search based on category selection.
解决方案 Your interface is a little confusing as you seem to use the same input select for both assigning categories to todos and filtering, I'll get to that at the end of the answer, but for now, I just used the category selector for both entering data and filtering by category.
The answer to your question is extremely simple. You just filter by the category as well as by the completed state. Like this:
var shownTodos = todos.filter(function(todo) {
return(todo.category === this.state.newCategory);
}, this).filter(function (todo) {
switch (this.state.nowShowing) {
case app.ACTIVE_TODOS:
return !todo.completed;
case app.COMPLETED_TODOS:
return todo.completed;
default:
return true;
}
}, this);
I would add some more buttons along the bottom for the categorical currently on display. You would also add a new set of statuses like nowShowing
for the category like nowShowingCategory
. The buttons would set this to the 3 values of category, and you would use that variable in the above filter instead of newCategory
from my example.
这篇关于在 React Js 中过滤 Todo 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 React Js 中过滤 Todo 列表
基础教程推荐
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01