我正在构建一个React组件,它接受JSON数据源并创建一个可排序的表。 每个动态数据行都有一个唯一的键分配给它,但我仍然得到一个错误:

数组中的每个子元素都应该有一个唯一的“key”道具。 检查TableComponent的渲染方法。

我的TableComponent渲染方法返回:

<table>
  <thead key="thead">
    <TableHeader columns={columnNames}/>
  </thead>
  <tbody key="tbody">
    { rows }
  </tbody>
</table>

TableHeader组件是单行,也有一个唯一的键赋给它。

行中的每一行都是由一个具有唯一键的组件构建的:

<TableRowItem key={item.id} data={item} columns={columnNames}/>

TableRowItem看起来是这样的:

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c) {
          return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

是什么导致唯一键道具错误?


当前回答

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c, i) {
          return <td key={i}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

这样问题就解决了。

其他回答

在我的例子中,将id设置为tag

<tbody key={i}>

问题解决了。

在使用Mongo数据的情况下,您可以使用_id属性

arr.map((cell) =>
  <li key={cell._id}>{cell}
  </li>
);

您应该为tbody where的每个子键使用唯一的值

该值不能与其同级值相同 不应该在渲染之间改变

例如,键值可以是数据库id或UUID(通用唯一标识符)。

这里的键是手动处理的:

<tbody>
  {rows.map((row) => <ObjectRow key={row.uuid} />)}
</tbody>

你也可以让React使用React. children . toarray来处理键

<tbody>
  {React.Children.toArray(rows.map((row) => <ObjectRow />))}
</tbody>

您的密钥应该是唯一的。就像一个唯一的id。你的代码应该是这样的

<div>
 {products.map(product => (
   <Product key={product.id}>
    </Product>
    ))}
  </div>

检查:key = undef !!

你也得到了警告信息:

Each child in a list should have a unique "key" prop.

如果你的代码是完全正确的,但是如果打开

<ObjectRow key={someValue} />

someValue未定义!!请先检查一下这个。你可以节省时间。