繁体   English   中英

警告:列表中的每个孩子都应该有一个唯一的“关键”道具。 检查 `RenderComments` 的渲染方法

[英]Warning: Each child in a list should have a unique "key" prop. Check the render method of `RenderComments`

我知道我需要一个唯一的密钥,但我应该在哪里添加它? 这是 JSON 文件:

"comments": [
    {
      "dishId": 1,
      "rating": "4",
      "author": "Customer1",
      "comment": "This is a test Comment",
      "date": "2022-02-04T12:34:15.994Z",
      "id": 21
    }
]

RenderComment 的渲染方法如下:

function RenderComments({ comments, postComment, dishId }) {
    if (comments != null)
        return (
            <div className="col-12 col-md-5 m-1">
                <h4>Comments</h4>
                <ul className="list-unstyled">
                    <Stagger in>
                        {comments.map((comment) => {
                            return (
                                <Fade in key={comment._id}>
                                    <li>
                                        <p>{comment.comment}</p>
                                        <p><b>-{comment.author}</b>,
                                            &nbsp;
                                            {new Intl.DateTimeFormat('en-US', {
                                                year: 'numeric',
                                                month: 'long',
                                                day: '2-digit'
                                            }).format(new Date(comment.date))}
                                        </p>
                                    </li>
                                </Fade>
                            );
                        })}
                    </Stagger>
                </ul>
                <CommentForm dishId={dishId} postComment={postComment} />
            </div>
        );
    else
        return (
            <div></div>
        );
}

编辑:我尝试将“comments._id”更改为“comments.id”,但没有帮助。

我看到你在 map 中使用了_id属性,但在 json 中我们有id属性。 尝试将key={comment._id}更改为key={comment.id} 因为如果对象没有_id道具,您的密钥将始终undefined

暂无
暂无

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

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