ReactJS - 尽管关键元素缺失密钥

时间:2017-10-07 17:53:08

标签: reactjs

我面对我的道具组件的常见Warning: Each child in an array or iterator should have a unique "key" prop错误,尽管为返回的div元素设置了我的数组的unqiueID键,但我看到了这个警告。我把它设置在错误的元素上吗?它可能与嵌套的map

有关

JSON示例:

{
annotationId: 117,
title: "Test",
discovery: "Test 123",
annotation_comments: [{
annotationCommentId: 12,
comment: "Lorem Ipsum"
}]
}

详细错误:

in AnnotationCard (created by AnnotationFeed)
    in AnnotationFeed (created by AnnotationFeedContainer)
    in div (created by AnnotationFeedContainer)
    in AnnotationFeedContainer (created by Annotation)
    in div (created by Annotation)
    in Annotation

组件:

//Loop through JSON and component
const AnnotationFeed = props => {
    return (
        <div>
        { 
            props.annotations.map((annotation, index) => {
                return (
                    <AnnotationCard {...annotation}>
                        { annotation.annotation_comments.map((comment, i) => <Comments {...comment} />)}
                    </AnnotationCard>
                );
            })
        }
        </div>
    )
}

const AnnotationCard = props => {
    return (
        <div key={props.annotationIdHash}>
            <h4>{props.title}</h4>
            <p>{props.discovery}</p>
        </div>
    )
}

const Comments = props => {
    return (
        <div key={props.annotationCommentId}>
            <h4>{props.comment}</h4>
        </div>
    )
}

2 个答案:

答案 0 :(得分:3)

你需要钥匙

<AnnotationCard {...annotation} key={index}>

在这里

<Comments {...comment} key={i}/>

答案 1 :(得分:0)

错误清楚地表明AnnotationCardComments组件需要一个关键属性。所以你应该为这两个组件设置一个键属性,而不是它们里面的div标签。