【问题标题】:ReactJS keep asking for key: Warning: Each child in a list should have a unique "key" prop. Check the render method of `PostCard`ReactJS 不断询问密钥:警告:列表中的每个孩子都应该有一个唯一的“密钥”道具。检查`PostCard`的渲染方法
【发布时间】:2021-07-04 11:47:37
【问题描述】:

我不知道为什么即使添加了密钥,反应仍然不断要求密钥。

我有一个渲染一些帖子的组件,但每个帖子都在它自己的组件中渲染,并且它位于来自 Swiper

的组件内

我的组件如下所示:

export default function Posts() {

const postsCards = posts.map(post => {
   return <SwiperSlide className="w-25" key={post._id}>
              <PostCard post={post} key={post._id}/>
          </SwiperSlide>
})

return (
<div className="container">
    <h4>Top posts</h4>
    <Swiper
      slidesPerView= 'auto'
      spaceBetween= {10}
      observer= {true}
      observeParents={true}
    >
        {postsCards}
    </Swiper>
</div>
)
}

【问题讨论】:

  • 它说键应该是唯一的。使用 post._id 检查它们是否不相同。此外,您可能还想显示明信片代码。

标签: reactjs react-key-index


【解决方案1】:

正如我所见,SwiperSlide 和 PostCard 的键相同。每个人都应该有一个唯一的密钥。

【讨论】:

  • 我认为这不是问题,因为即使我删除它,它仍然会抛出错误,我已经添加了“PostCard”的密钥以检查它是否可以解决错误
【解决方案2】:

将 key 属性添加到父组件 SwiperSlide 就足够了。

【讨论】:

    【解决方案3】:

    正如@user9779830所提到的

    SwiperSlide 和 PostCard 具有相同的键。我创建了一个解决方案,其中 PostCard 组件的键设置为 post._id 的哈希:

    hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)
    
    export default function Posts() {
    
    const postsCards = posts.map(post => {
       return <SwiperSlide className="w-25" key={post._id}>
                  <PostCard post={post} key={hashCode(post._id.toString())}/>
              </SwiperSlide>
    })
    
    return (
    <div className="container">
        <h4>Top posts</h4>
        <Swiper
          slidesPerView= 'auto'
          spaceBetween= {10}
          observer= {true}
          observeParents={true}
        >
            {postsCards}
        </Swiper>
    </div>
    )
    }
    

    如您所见,两个组件的键将不同,因为 PostCard 组件使用 'post._id' 的哈希

    【讨论】:

    • 您只需要 SwiperSlide 组件的密钥,而不需要 PostCard。
    • 让我们看看什么对用户有用,如果仅通过设置 SwiperSlide 组件的键来解决问题,我将编辑我的答案。
    • 我试过这个方法,但并没有解决问题。请帮帮我
    【解决方案4】:

    这并不完全是一个解决方案,但现在使用索引作为键,可以让您识别您的 post._id 是否是唯一的。

    const postsCards = posts.map((post, index) => {
       return <SwiperSlide className="w-25" key={`${post._id}-${index}`}>
                  <PostCard post={post}/>
              </SwiperSlide>
    })
    

    如果上面的代码不再返回错误,那么很可能你在你的帖子数组中重复了posts

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2021-03-26
      • 2020-09-06
      • 2023-02-17
      • 2019-01-15
      相关资源
      最近更新 更多