问题描述
我是 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 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End
相关推荐
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22
前端开发问题
182
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23
前端开发问题
262
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18
前端开发问题
301
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18
前端开发问题
125
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17
前端开发问题
437
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11
前端开发问题
455
热门文章
1错误 [ERR_REQUIRE_ESM]:不支持 ES 模块的 require()
2vue中yarn install报错:info There appears to be trouble with you
3为什么 Chrome(在 Electron 内部)会突然重定向到 chrome-error://chromewebdat
4“aria-hidden 元素不包含可聚焦元素"显示模态时的问题
5使用选择器在 CSS 中选择元素的前一个兄弟
6js报错:Uncaught SyntaxError: Unexpected string
7layui怎么刷新当前页面?
8将模式设置为“no-cors"时使用 fetch 访问 API 时出错
热门精品源码
最新VIP资源
1多功能实用站长工具箱html功能模板
2多风格简历在线生成程序网页模板
3论文相似度查询系统源码
4响应式旅游景点宣传推广页面模板
5在线起名宣传推广网站源码
6酷黑微信小程序网站开发宣传页模板
7房产销售交易中介网站模板
8小学作业自动生成程序


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)