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

React列表渲染警告:使用MongoDB的_id作为key仍报错

Hey, let's figure out why that key warning is still popping up even though you've tried several approaches. Looking closely at your code, I spotted a nested map that's missing a key prop—this is almost certainly the culprit!

You added a key to the outer <FieldWrapper> using item._id, which is good, but take a look at the color list inside each product:

{item.colors.map((color:any)=>(
    <div style={{backgroundColor:color}}></div>
))}

React checks every list item generated by map() for a unique key, including these inner color divs. Since they don't have keys, React throws the warning you're seeing, and you might have mistakenly attributed it to the outer product list.

Fix the Inner Map First

Fix this by adding a unique key to each color div. If your color values are unique (like distinct hex codes or color names), you can use the color itself as the key:

{item.colors.map((color:any)=>(
    <div key={color} style={{backgroundColor:color}}></div>
))}

If there's a chance of duplicate colors in the same product (unlikely, but possible), combine the product's ID with the index to guarantee uniqueness:

{item.colors.map((color:any, index:number)=>(
    <div key={`${item._id}-color-${index}`} style={{backgroundColor:color}}></div>
))}

If the Warning Persists

If fixing the inner map doesn't resolve the issue, check these additional points:

  • Verify item._id uniqueness: Add console.log(item._id) inside the outer product map to ensure no duplicate IDs exist in currentProducts. Sometimes duplicate entries can sneak in if the getAllProducts action runs multiple times without resetting the state properly.
  • Check initial Redux state: Make sure allProducts is initialized as an empty array ([]) in your slice, not null or undefined—this prevents unexpected rendering before data loads.
  • Skip indexes for outer keys: You mentioned trying indexes, but they're only safe for static lists that never reorder, add, or remove items. Stick with item._id since it's a stable, unique MongoDB identifier.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:35:13