数组或迭代器中的每个子代都应具有唯一的“键". reactjs中的prop [英] Each child in an array or iterator should have a unique "key" prop in reactjs

查看:63
本文介绍了数组或迭代器中的每个子代都应具有唯一的“键". reactjs中的prop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全感到困惑,因为我在控制台中犯了错误,并且阅读了reactjs文档和有关stackoverflow的所有技巧,但是我无法理解是什么问题. 我看到了书名列表({item.volumeInfo.title}),但是控制台有错误.

I totally confused, because I have mistake in my console and I read reactjs documentation and all tips on stackoverflow, but I can't unterstand what problem is. I see list of book's titles ({item.volumeInfo.title}), but console has error.

这是我的代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';

class BookList extends Component {
    renderBook(mainData) {
        return(
             <ul>
                {mainData.items.map((item, i) => {
                    return <li key={i} item={item}>{item.volumeInfo.title}</li>
                    })}
             </ul>
        )
    }

    render(){
        return (
            <div className="book-row">
                <div className="book-info">
                    {this.props.book.map(this.renderBook)}
                </div>
            </div>
        );
    }
}

function mapStateToProps({book}) {
    return {book};
}

export default connect(mapStateToProps)(BookList);

它是API响应的一部分:

It is part of API response:

{ "kind": "books#volumes", 
 "totalItems": 288, 
 "items": [ 
  {
   "kind": "books#volume",
   "id": "yXlOAQAAQBAJ",
   "etag": "CG7f2mQ+7Nk",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/yXlOAQAAQBAJ",
   "volumeInfo": {
    "title": "Nineteenth Century Home Architecture of Iowa City",
    "subtitle": "A Silver Anniversary Edition"

我试图做以下按键:

键= {item.etag},键= {i},键= {item.volumeInfo.title}

但错误仍然存​​在.

请帮助.

非常感谢您.

推荐答案

由于您正在book上进行映射:

Since you are mapping over book:

{this.props.book.map(this.renderBook)}

ul还需要一个key道具:

renderBook(mainData, bookIdx) {
        return(
             <ul key={bookIdx}>
                {mainData.items.map((item, i) => {
                    return <li key={i} item={item}>{item.volumeInfo.title}</li>
                    })}
             </ul>
        )
    }

这是因为将有许多ul兄弟姐妹,而React需要说明差异(与li相同).

This is because there will be many ul siblings and React needs to tell the difference (same as with li).

但是,最好(如果可能)使用不是数组索引的键.因此,如果bookitem具有唯一的标识符,则最好使用它.

However, it is better (if possible) to use a key that is not the index of the array. So, if book and item have a unique identifier, it would be best to use that.

因此,您似乎在提供的示例数据之外还有另一个数组:

So, it looks like you have another array outside of the sample data you provided:

[
 { "kind": "books#volumes", 
   "totalItems": 288, 
   "items": [ 
    {

这篇关于数组或迭代器中的每个子代都应具有唯一的“键". reactjs中的prop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆