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._iduniqueness: Addconsole.log(item._id)inside the outer product map to ensure no duplicate IDs exist incurrentProducts. Sometimes duplicate entries can sneak in if thegetAllProductsaction runs multiple times without resetting the state properly. - Check initial Redux state: Make sure
allProductsis initialized as an empty array ([]) in your slice, notnullorundefined—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._idsince it's a stable, unique MongoDB identifier.
内容的提问来源于stack exchange,提问作者Roman

