ReactのListとKey

ReactでList(ObjectのArray)を描画する際、mapを利用して各Objectの項目をセットする。

var data = [
        {id: 1, author: "Pete Hunt", text: "This is one comment"},
        {id: 2, author: "Jordan Walke", text: "This is *another* comment"}
];

var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function (comment) {
      return (
        <div author={comment.author}>
          {comment.text}
        </div>
      );
    });
    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

 

もし描画する際に、各ObjectにユニークなKeyを持たせていない場合は警告が出る。

react.js:20541 Warning: Each child in an array or iterator should have a unique "key" prop.

 

以下のように、keyに何かしらのユニークな値を持たせると、以下の警告は消える。

<div author={comment.author} key={comment.id}>

参考文献