簡體   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