警告:列表中的每个孩子都应该有一个唯一的“键".支柱 [英] Warning: Each child in a list should have a unique "key" prop
问题描述
我正在使用谷歌图书 API 构建一个应用程序,我似乎正在向列表中的每个孩子传递一个唯一的密钥,但错误不会消失.我一定是做错了什么,但我不确定是什么.
const BookList = (props) =>{//映射所有书籍项目,为其中的每个项目创建一张新卡片列表const 书籍 = props.books.data.items.map((book) => {控制台.日志(书.id)返回 (<div className="col col-lg-4 grid-wrapper"><书卡键={book.id}图像={book.volumeInfo.imageLinks.thumbnail}标题={book.volumeInfo.title}作者={book.volumeInfo.authors[0]}描述={book.volumeInfo.description}previewLink={book.volumeInfo.previewLink}购买链接={book.saleInfo.buyLink}/>
);})返回 (<div>{书籍}</div>);}
请注意,在 const 书籍中返回后,我有一个 console.log(book.id),它将在控制台中显示所有 10 个唯一的 id 键.但是当我尝试使用 key={book.id} 将它传递给这个组件的子组件时,我收到了这个错误.
key
需要放在最外层的返回元素上.在您的特定情况下,这意味着更改此内容:
<书卡键={book.id}为此:
<书卡I'm building an app using the google books API and I appear to be passing a unique key to each child in the list, but the error won't go away. I must be doing something wrong but I'm not sure what.
const BookList = (props) => {
//map over all of the book items to create a new card for each one in
the list
const books = props.books.data.items.map((book) => {
console.log(book.id)
return (
<div className="col col-lg-4 grid-wrapper">
<BookCard
key={book.id}
image={book.volumeInfo.imageLinks.thumbnail}
title={book.volumeInfo.title}
author={book.volumeInfo.authors[0]}
description={book.volumeInfo.description}
previewLink={book.volumeInfo.previewLink}
buyLink={book.saleInfo.buyLink}
/>
</div>
);
})
return (
<div>{books}</div>
);
}
Notice that after the return in const books I have a console.log(book.id), which will display all 10 unique id keys in the console. But when I try to pass it to the child of this component using key={book.id}, I get this error.
解决方案 The key
needs to go on the outermost returned element. In your specific case, that means changing this:
<div className="col col-lg-4 grid-wrapper">
<BookCard
key={book.id}
to this:
<div className="col col-lg-4 grid-wrapper" key={book.id}>
<BookCard
这篇关于警告:列表中的每个孩子都应该有一个唯一的“键".支柱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文