独特的关键支柱?

时间:2018-05-31 14:28:00

标签: reactjs key unique

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

"警告:数组或迭代器中的每个子项都应该有一个唯一的"键"丙"

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



     Student: {this.props.comments.comment}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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