You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用lodash的times方法批量渲染React组件时如何获取index作为key

你可以直接在_.times的回调函数中接收索引参数,lodash的times方法默认会将当前迭代的索引作为第一个参数传入回调,不需要额外封装逻辑或者生成随机值:

export const MyComponent: React.FC<{times: number}> = ({ times }) => {
  return (
    <>
      {_.times(times, (index) => (
         <div 
           key={index}
           className="bg-white border-4 border-white md:rounded-md md:p-2 content-center my-4 shadow w-full">
         </div>
       ))}
    </>
  );
};

如果你的列表是静态的、后续不会发生列表项的增删、排序操作,用index作为key是完全符合React使用规范的,不会带来额外问题。

内容的提问来源于stack exchange,提问作者Loudrous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:24:03