React 数组渲染,key不确定怎么办

假设我有一个数组['tom','cat','jerry','tom','jerry'],长度不确定,并且可能有重复项,我需要利用这个数组来做渲染,key该如何选取?

阅读 3.6k
5 个回答

map个自增序列

function renderData(dataSource) {
  const items = {};

  return dataSource.map((item) => {
    items[item] = items[item] || 0;
    const key = items[item]++;

    return <div key={key}>{item}</div>;
  });
}

renderData(["tom", "cat", "jerry", "tom", "jerry"]);

这样?

需要把你的字符串数组 换成对象数组 这个对象带有唯一标识符的key

新手上路,请多包涵

无需排序,index就行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题