React新手开发Todo App:是否需新增renderList渲染已完成事项?
解决方案:复用renderList方法,无需单独编写
嘿,完全不用单独写两个renderList方法!其实只需要给现有的renderList加个参数,让它能接受过滤后的todos数组就行——既保持代码复用,又能轻松实现分栏展示的需求,一举两得。
步骤1:改造renderList,让它支持接收过滤后的数组
把原来的renderList改成接受filteredTodos参数,遍历这个参数渲染列表项即可:
renderList(filteredTodos) { return filteredTodos.map((todo) => { return ( <div className="item" key={todo.id}> <div className="right floated content"> <div className="ui buttons"> {/* 顺便补充切换完成状态的逻辑,点击按钮调用父组件的toggle方法 */} <button className={`ui icon ${todo.completed ? 'green' : 'gray'} button`} onClick={() => this.props.toggleTodo(todo.id)} > <i className="check icon"></i> </button> <button className="ui icon red button" onClick={() => this.props.delTodo(todo.id)}> <i className="times icon"></i> </button> </div> </div> <div className="content"> <div><b>Title</b></div> {/* 给已完成事项加个删除线,视觉上更直观 */} <div style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}> {todo.title} </div> </div> </div> ) }) }
步骤2:在render中拆分todos,分别传入renderList
先从props里拿到完整的todos数组,用filter方法拆分出待办和已完成的列表,再分别传给改造后的renderList:
render() { const { todos } = this.props; // 过滤出待办事项(completed为false) const pendingTodos = todos.filter(todo => !todo.completed); // 过滤出已完成事项(completed为true) const completedTodos = todos.filter(todo => todo.completed); return ( <div className="ui middle aligned divided list"> <h1> Pending </h1> {/* 空状态提示优化:如果没有待办,显示友好提示 */} {pendingTodos.length === 0 ? ( <div className="item">暂无待办事项🎉</div> ) : ( this.renderList(pendingTodos) )} <h1> Completed </h1> {completedTodos.length === 0 ? ( <div className="item">还没有完成的事项哦💪</div> ) : ( this.renderList(completedTodos) )} </div> ); }
为什么这种方式更好?
- 代码复用:只维护一个renderList方法,以后不管是修改item样式、添加新功能(比如编辑按钮),只需要改这一处就行,不用重复修改两个方法。
- 逻辑清晰:过滤逻辑和渲染逻辑分开,代码结构更直观,后期维护起来更省心。
- 扩展性强:如果以后需要加其他分类(比如“今天到期”“已过期”),只需要加对应的过滤条件,再调用renderList就行,不用新增重复代码。
内容的提问来源于stack exchange,提问作者code.cycling
相关产品推荐
相关产品推荐

