繁体   English   中英

如何在我的组件中添加一个键,同时在 React 中获取关键道具警告

[英]How do I add a key to my components, while getting the key prop warning in React

我在控制台上收到关键道具警告,想知道我的方法应该是什么:

我尝试向我的数组中添加一个 id 并将其添加到我的模板列表组件中,但似乎有些不对。

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `TemplateList`. See react-warning-keys for more information.
    in TemplateCard (created by TemplateList)
    in TemplateList (created by ActionPageNew)
    in div (created by ActionPageNew)
    in div (created by ActionPageNew)
    in ActionPageNew (created by Onboarding)
    in div (created by Onboarding)
    in Onboarding
    in Route (created by PrivateRoute)
    in PrivateRoute
    in Outlet (created by Route)
    in Route (created by PrivateRoute)
    in PrivateRoute
    in Routes
    in div (created by App)
    in App
    in Router (created by HistoryRouter)
    in HistoryRouter
    in Provider
    in i

我在数组对象中添加了一个 id,如下所示:

    templates = [
        {
            title: "Grocery List",
            description: "Description of what this things does so the reader can have info of",
            imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753993/groceries.png",
            id: 1,
        },

        {
            title: "Shopping Space",
            description: "blablabalblabla",
            imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753766/shopping.png",
            id: 2,
        },

        {
            title: "Travel Planning",
            description: "blablabalblabla",
            imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753885/travel.png",
            id: 3,
        },

        {
            title: "Travel",
            description: "blablabalblabla",
            imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753993/groceries.png",
            id: 4,
        },
    ];

然后我有我的模板列表卡组件,它映射和循环遍历数组:

在这里我添加了 key={item.id}

export type Template = {
    title: string;
    description: string;
    imgURL: string;
    id?: number;
};

type Props = {
    templates: Template[];
};

const TemplateList = ({ templates }: Props) => {
    return (
        <div className={styles.scrollContainer}>
            {templates.map((item) => (
                <TemplateCard
                    title={item.title}
                    description={item.description}
                    img={item.imgURL}
                    classNameToAdd={styles.cardContainer}
                    key={item.id}
                />
            ))}
        </div>
    );
};

export default TemplateList;

我不知道这是否是正确的方法,以及我应该在我的 TemplateCard 组件中添加的位置和内容:

type Props = {
    title: string;
    description: string;
    img: string;
    classNameToAdd?: string;
    classNameOnSelected?: string;
    id?: number;
};

const TemplateCard = ({ title, description, img, classNameToAdd, classNameOnSelected }: Props) => {
    const { aspectRatio, vmin } = useWindowResponsiveValues();
    let className = `${styles.card} ${classNameToAdd}`;

    const [selected, setSelected] = useState(false);

    const handleClick = () => {
        setSelected(!selected);
    };

    if (selected) {
        className += `${styles.card} ${classNameToAdd} ${classNameOnSelected}`;
    }

    return (
        <div style={card} className={className} onClick={handleClick}>
            <img style={imageSize} src={img}></img>
            <div style={cardTitle}>
                {title}
                {selected ? <BlueCheckIcon style={blueCheck} className={styles.blueCheck} /> : null}
            </div>
            <div style={descriptionCard}>{description}</div>
        </div>
    );
};

TemplateCard.defaultProps = {
    classNameOnSelected: styles.selected,
};

export default TemplateCard;

如果您直接在地图中添加该 ID 会更好,例如:

templates.map((item,index) => (
   <TemplateCard
      title={item.title}
      description={item.description}
      img={item.imgURL}
      classNameToAdd={styles.cardContainer}
      key={`TemplateCard-${index}`}
   />
))

然后将它传递给TemplateCard或将TemplateCard包装在一个 div 中并为其分配 id。

请记住,id 应该是唯一的,这就是我在索引之前添加文本的原因

由于您的templates数组已经为每个元素提供了一个id字段,因此我将使用它作为键而不是索引,以防将来您可能需要进行过滤和排序。

当 UI 涉及过滤和排序时,使用索引作为键可能会出现问题,因为在这种情况下索引无法唯一标识每个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM