如何在React.js中为数据列表添加索引值?
嘿,给你的React数据列表加索引其实挺容易的,咱们利用JavaScript数组map方法自带的索引参数就能搞定,我来一步步帮你修改代码:
方法一:修改现有createTasks方法
首先,把你的createTasks函数改成接受item和index两个参数,这样就能拿到当前项的索引了(如果想要从1开始计数,就用index + 1,直接用index就是从0开始):
createTasks(item, index) { const itemNumber = index + 1; // 从1开始的序号 return ( <li key={item._id}> {itemNumber}. {item.name} <a href="#" className="button bg_green" onClick={() => this.edit(item._id)}>Edit</a> <a href="#" className="button bg_red" onClick={() => this.delete(item._id)}>Delete</a> </li> ); }
然后,找到你render方法里遍历列表的代码,原来应该是用this.props.items.map(this.createTasks),现在要改成传递索引参数:
render() { // 给map加上第二个参数index,传给createTasks const todoEntries = this.props.items.map((item, index) => this.createTasks(item, index)); return ( <ul className="theList"> {todoEntries} </ul> ); }
方法二:直接在map里渲染(更简洁)
如果你觉得分开写createTasks麻烦,也可以直接在render的map里完成渲染,省得单独维护一个方法:
render() { return ( <ul className="theList"> {this.props.items.map((item, index) => ( <li key={item._id}> {index + 1}. {item.name} <a href="#" className="button bg_green" onClick={() => this.edit(item._id)}>Edit</a> <a href="#" className="button bg_red" onClick={() => this.delete(item._id)}>Delete</a> </li> ))} </ul> ); }
⚠️ 注意:这里列表项的key一定要用item._id这种唯一标识,别用索引当key!因为如果列表有添加、删除、排序操作,索引会跟着变化,React用索引当key可能会导致渲染异常哦。
内容的提问来源于stack exchange,提问作者satya
相关产品推荐
相关产品推荐

