【问题标题】:Unique key prop?独特的钥匙道具?
【发布时间】:2018-11-10 14:34:41
【问题描述】:

我不知道如何解决这个警告信息??

“警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”属性。

  let theComments = 
  this.props.state.studentCommentReducer.studentCommentReducer.map((comments) => {
  return <CommentsItem key={comments.id} comments={comments} />;
  });



     Student: {this.props.comments.comment}

【问题讨论】:

  • 是不是像把 cmets.id 改成别的一样简单?

标签: reactjs key unique


【解决方案1】:

在某种程度上,您需要为每个项目指定一个键。你可以这样做

...map((comments) => {
  return <CommentsItem key={comments.id} comments={comments} />;
});

...map((comments, i) => {
  return <CommentsItem key={i} comments={comments} />;
});

参考:https://reactjs.org/docs/lists-and-keys.html#keys-must-only-be-unique-among-siblings

【讨论】:

    【解决方案2】:

    您需要为每个映射的CommentsItempreferably not the index of the array 指定一个唯一键。

    在您的代码中,确保 comments.id 是唯一的。这将解决您收到的警告消息。

    【讨论】:

      【解决方案3】:

      您只能将索引用作静态列表的键。尝试使用其他列表作为键

      【讨论】:

        猜你喜欢
        • 2021-03-20
        • 1970-01-01
        • 2022-11-25
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 2016-07-21
        • 1970-01-01
        相关资源
        最近更新 更多