如何在我的组件中添加密钥,同时在 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 涉及筛选和排序时,使用索引作为键可能会出现问题,因为在这种情况下索引无法唯一标识每个元素。