在复杂的 React 组件中查找重复键

IT技术 reactjs duplicates key components
2021-05-17 11:43:55

我有一个react组件,它一次生成许多键,我不确定哪个不是唯一的。错误如下。有什么简单的方法可以帮助调试吗?谢谢!

react.js:19500 警告:数组或迭代器中的每个子项都应该有一个唯一的“键”属性。检查 的渲染方法MyGrid有关更多信息,请参阅 https://fb.me/react-warning-keys。

2个回答

这是一个警告,您没有分配键,而不是它实际上不是唯一的,消息的下一行应该告诉您到底什么是有问题的元素 - 请参阅下面的示例 in div (created by CardsComponent)

warning.js:36 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `CardsComponent`. See fb.me/react-warning-keys for more information. in div (created by CardsComponent)

如果您想进一步调试,则完成测试,ReactElementValidator.validateExplicitKey其中仅检查元素键是否为非空,不检查同级键之间的唯一性...

function validateExplicitKey(element, parentType) {
  if (!element._store || element._store.validated || element.key != null) {
    return;
  }
  // if it gets here it has failed and you will be warned

这里有趣的部分是element.key != null因为其他人已经被验证过

单击以展开控制台中的错误以显示堆栈跟踪。按照之前的呼叫进行操作createElementWithValidation,它应该会显示出罪魁祸首的行号。

记录您在那里使用的密钥。如果有一吨,把它们放在一个数组中[].filter((e, i, a) => a.indexOf(e) !== i)