通过`map`函数调用传入键

时间:2016-08-19 18:09:54

标签: javascript reactjs

我收到一个关于阵列中没有唯一键的每个孩子的警告。

const ITEMS = [
    {
        "name": "blah", displayName: "Blah!"
        "name": "blah1", displayName: "Blah1!"
    },
    {
        "name": "blah2", displayName: "Blah2!"
        "name": "blah3", displayName: "Blah3!"
    }
]

item: function(i) {
    return (
        <div key={i.name}>
            <h1>{i.displayName}</h1>
        </div>
    )
}

render: function() {
    return (
        <div>
            {_.chain(ITEMS).map(this.item, this).value()} # I need to pass in a key here?
        </div>
    )
}

我在一个月前发布过一个类似的问题:"Each child in an array should have a unique key prop" only on first time render of page。在这种情况下,我需要在调用map函数时通过item()传递密钥。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

JavaScript的map将数组的索引作为map函数的第二个参数传递。

因此,您应该只需将索引添加到item

item: function(currentValue, idx) {
    return (
        <div key={currentValue.name + '-' + idx}>
            <h1>{currentValue.displayName}</h1>
        </div>
    )
}

这将确保密钥是唯一且稳定的。

在您当前的实施中,i.name可能不是唯一的。在这种情况下,您将收到反应警告。

此外,此对象文字可能无法执行您的操作:

{
    "name": "blah", displayName: "Blah!"
    "name": "blah1", displayName: "Blah1!"
}

对象中的name之类的键必须是唯一的,否则您可能会得到未定义的行为。

相关问题