简体   繁体   English

在反应组件中嵌套 map function ->“唯一的“关键”道具”

[英]nested map function in a react component -> "unique "key" prop"

How would i get a proper Key Value in this component:我将如何在此组件中获得正确的键值:

 {var.map((building, index) => {
        const handles = building.buildingVertices.map((point) => {
          return (
            <DrawingHandle
              key={`${index}_handle${point.id}`}
            />
          )
        })
        return (
          <>{handles}</> //<--- how do i get a key in here?
        )
      })}

since <>{handles}</> does not have a key value, i get the error: Warning: Each child in a list should have a unique "key" prop.由于<>{handles}</>没有键值,我收到错误: Warning: Each child in a list should have a unique "key" prop.

Thanks a lot!非常感谢!

You have nested array structure, that is why react does not understand this case.你有嵌套的数组结构,这就是为什么反应不理解这种情况。 You can use array.flatMap to flatten nested array and just return it:您可以使用array.flatMap来展平嵌套数组并返回它:

{var.flatMap((building, index) => {
    return building.buildingVertices.map((point) => {
        return (
          <DrawingHandle
              key={`${index}_handle${point.id}`}
          />
        )
    })
})}

Or you can use full Fragment syntax and provide the key:或者您可以使用完整的Fragment语法并提供密钥:

{var.map((building, index) => {
    const handles = building.buildingVertices.map((point) => {
      return (
        <DrawingHandle
          key={`${index}_handle${point.id}`}
        />
      )
    })
    return (
      <Fragment key={index}>{handles}</Fragment>
    )
})}

Why not assign a key to a return div?为什么不为返回 div 分配一个键?

{var.map((building, index) => {
        const handles = building.buildingVertices.map((point) => {
          return (
            <DrawingHandle
              key={`${index}_handle${point.id}`}
            />
          )
        })
        return (
          <div key={index}>{handles}</div>
        )
      })}

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

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