【问题标题】:React "Warning: Encountered two children with the same key"反应“警告:遇到两个孩子用相同的钥匙”
【发布时间】:2022-02-19 17:08:32
【问题描述】:

我有一个映射卡的反应应用程序,并且每张卡都有唯一的 id,尽管我在控制台中遇到了一些不是唯一的错误:

警告:遇到两个孩子使用相同的密钥,2294264。钥匙 应该是唯一的,以便组件在整个过程中保持其身份 更新。非唯一键可能会导致子项重复和/或 省略 - 行为不受支持,将来可能会改变 版本。

这是构建我的卡片结构的代码:

function CreateCards(doc) {
  return (
    <SimpleCard
      key={doc.newsid}
      theCardId={doc.newsid}
      categorietitle={doc.categorietitle}
      newstitle={doc.newstitle}
      date={format(new Date(doc.date), "dd/MM/yyyy")}
      thenews={doc.thenews}
      newsurl={doc.newsurl}
    />
  );
}

这是映射卡片的代码:

      <div className="general-card1">
        {this.state.noPlaceFound ? (
          <h3 className="noPlaceFound">
            <i className="fas fa-exclamation-circle fa-sm WarnIcon"></i>
            لا يوجد نتائج
          </h3>
        ) : (
          this.state.WasMap.map((v) => CreateCards(v._source))
        )}
      </div>

你能帮帮我吗

【问题讨论】:

  • 键应该是唯一的。由于某种原因,它们不应该被索引并且不应该重复。 reactjs.org/docs/lists-and-keys.html
  • 我很确定 React 不会弥补这一点,你的数据中有一个重复的 newsid。你能分享正在映射的数据吗?
  • @DrewReese 我之所以这么说,是因为我拿走了包含所有 id 的整个 json 文件并使用 python 检查重复没有重复

标签: javascript reactjs


【解决方案1】:

这是因为当您在地图中渲染组件列表时,每个组件都应该具有唯一的键属性。由 React 区分它们。尝试这样做:

 <div className="general-card1">
        {this.state.noPlaceFound ? (
          <h3 className="noPlaceFound">
            <i className="fas fa-exclamation-circle fa-sm WarnIcon"></i>
            لا يوجد نتائج
          </h3>
        ) : (
          this.state.WasMap.map((v, index) => <CreateCards doc ={v._source } key ={index}/>)
        )}
  </div>
function CreateCards({doc}) {
  return (
    <SimpleCard
      key={doc.newsid}
      theCardId={doc.newsid}
      categorietitle={doc.categorietitle}
      newstitle={doc.newstitle}
      date={format(new Date(doc.date), "dd/MM/yyyy")}
      thenews={doc.thenews}
      newsurl={doc.newsurl}
    />
  );
}

【讨论】:

  • OP 的代码正在运行,问题在于特定键。通常应避免使用映射数组索引,仅作为没有其他唯一键值可用的最后手段。
猜你喜欢
  • 2018-10-06
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2017-09-11
  • 2017-06-01
  • 1970-01-01
相关资源
最近更新 更多