【问题标题】:Warning: Each child in a list should have a unique "key" prop but i have key props [duplicate]警告:列表中的每个孩子都应该有一个唯一的“关键”道具,但我有关键道具 [重复]
【发布时间】:2021-09-01 22:40:42
【问题描述】:

提供的答案并没有提示我这里的问题是什么。所以我在控制台中收到以下错误:

react-jsx-dev-runtime.development.js?bfcc:117 Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Feed`. See https://reactjs.org/link/warning-keys for more information.

这是我在 return 语句中的代码:

return (
    <>
      <Header></Header>
      <div className={hfstyles.feed} style={{ 'maxWidth': '980px;', 'textAlign': 'center', 'margin': '0 auto', 'padding': '5em 0' }}>

        {feed.map((post, index) => {
          const postBefore = index == 0 ? new Date() : feed[index - 1].createdAt;
          return randomIndex == index ? (
            <>
            <PostBasic
              post={post}
              postBefore={postBefore}
              key={post.id}
            />
            <RandomMessage/>
            </>)
            :
            (<PostBasic
              post={post}
              postBefore={postBefore}
              key={post.id}
            />
          );
        })}

        {feedEnd == true && (
          <p>Thats it</p>
        )}

      </div>
      <Footer sticky={false}></Footer>
    </>
  );

我还尝试为&lt;RandomMessage/&gt; component 提供key 属性,并尝试将密钥从数据库ID post.id 更改为地图的index,而不进行任何更改

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    你必须将 key props 传递给 fragment(),而不是 PostBasic。

    这样使用,

    改变这个

    (
      <>
        <PostBasic post={post} postBefore={postBefore} key={post.id} />
        <RandomMessage />
      </>
    );
    

    (<React.Fragment key={post.id}>
      <PostBasic post={post} postBefore={postBefore} />
      <RandomMessage />
    </React.Fragment>
    )
    

    【讨论】:

    • 非常感谢您的帮助!
    猜你喜欢
    • 2023-04-07
    • 2019-08-04
    • 2021-01-12
    • 2022-06-28
    • 2021-06-17
    • 2021-12-05
    • 2019-12-05
    • 2021-09-05
    • 2020-03-01
    相关资源
    最近更新 更多