首页 > 解决方案 > 尽管添加了唯一键,但反应还是会发出警告

问题描述

尽管向元素key={item.?key}添加了唯一键,但我仍然收到以下警告:

警告:列表中的每个孩子都应该有一个唯一的“关键”道具。 使用 . 检查顶级渲染调用<ol>

import React from 'react';

function myComponent(...data) {
  return (
    <section className="my-component">
      <ol className="my-component__cards">
        {data[0].items.map((item) => (
          <a key={item?.key} className="my-component__slide">
            <li>
              <h3>{item?.title?.rendered}</h3>
              <p dangerouslySetInnerHTML={{ __html: item?.content?.rendered }} />
            </li>
          </a>
        ))}
      </ol>
    </section>
  );
}

export default myComponent;

谢谢

标签: reactjs

解决方案


如果您item有一个名为 as 的唯一道具key,那么这必须很好,您需要替换?!. (打字稿问题,打字稿解决方法:D)但如果您不确定,只需index用作关键道具。

{data[0].items.map((item, index) => (
  <a key={index} ...


推荐阅读