2017-06-14 50 views
0

我试图创建一个包含数组对象的窗体。我得到错误Encountered two children with the same key, 1:$ [object Object] .。我如何创建一个唯一的密钥?在映射数组对象时创建唯一键

renderPositions() { 
    const profileCandidateCollection = this.props.profileCandidate; 
    const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions; 

    if (careerHistoryPositions) { 
    return careerHistoryPositions.map((key, position) => { 
     return (
     <CareerHistoryPositionsUpdateForm 
      key={key} 
      company={position.company} 
      title={position.title} 
     /> 
    ) 
    }) 
    } 
} 

回答

2

你几乎是正确的。如果你想使用索引在map元素至上而指数进入第二:

return careerHistoryPositions.map((position, key) => { 
    return (
    <CareerHistoryPositionsUpdateForm 
     key={key} 
     company={position.company} 
     title={position.title} 
    /> 
    ) 
}) 

该指数适用于密钥,但in React it's discouraged。相反,请使用唯一的标识符:

选择密钥的最佳方法是使用一个字符串,该字符串在其兄弟中唯一标识一个列表项。大多数情况下,你会使用的ID从您的 数据项:

所以对于被添加到careerHistoryPositions添加另一个密钥与唯一的ID,并用其作为列表项中的每个项目。在过去,我使用UUID包中的v4方法来创建唯一的ID。

+0

谢谢,我在React文档中看过。您建议为每个对象创建一个唯一的ID是个好主意。 – bp123