简体   繁体   中英

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

I know I need a unique key, but where do I add it? This is the JSON file:

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

The RenderComment's render method is as follows:

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>
        );
}

Edit: I have tried changing "comments._id" to "comments.id" but its not helping.

I see that you use _id prop in map, but in json we have id prop. Try to change key={comment._id} to key={comment.id} . Because if the objects doesn't have _id prop, your key always will be undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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