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

React从MongoDB过滤产品时出现列表key属性唯一警告求助

问题解决:React列表渲染的"unique key"警告

警告内容

Warning: Each child in a list should have a unique "key" prop.
Check the render method of Products.
at Product (http://localhost:3000/static/js/bundle.js:1754:5)
at Products (http://localhost:3000/static/js/bundle.js:1904:5)
...(省略后续调用栈)

问题根源

你的Products组件中用key={item.id}给列表项设置key,但MongoDB默认生成的文档主键字段是_id而非id。这会导致设置的key要么是undefined,要么因无有效唯一标识出现重复,触发React的key唯一性警告。

修复方案

将map渲染时的key替换为MongoDB文档的_id字段(该字段在集合中天生唯一)。如果_id是MongoDB默认的ObjectId类型,需要转为字符串使用:

修改后的Products.jsx关键代码

return (
  <Container >
    {filteredProducts.map((item) => (
      <Product item={item} key={item._id.toString()} />
    ))}
  </Container>
);

如果你的后端已经通过配置(比如Mongoose的toJSON)将_id自动转为字符串,直接使用key={item._id}即可。

额外排查点

若修改后警告仍存在,请确认:

  • filteredProducts中的每个item确实拥有唯一的_id值
  • Product组件内部是否存在未设置唯一key的列表渲染元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:45:45