了解React.js中数组子项的唯一键

帅比萌擦擦* 提交于 2020-07-28 04:14:42

问题:

I'm building a React component that accepts a JSON data source and creates a sortable table. 我正在构建一个接受JSON数据源并创建可排序表的React组件。
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of: 每个动态数据行都有一个分配给它的唯一键,但是我仍然遇到以下错误:

Each child in an array should have a unique "key" prop. 数组中的每个子代都应具有唯一的“键”道具。
Check the render method of TableComponent. 检查TableComponent的渲染方法。

My TableComponent render method returns: 我的TableComponent渲染方法返回:

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

The TableHeader component is a single row and also has a unique key assigned to it. TableHeader组件是单行,还为它分配了唯一的键。

Each row in rows is built from a component with a unique key: row中的每一rows都是由具有唯一键的组件构建的:

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

And the TableRowItem looks like this: 并且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>
    )
  }
});

What is causing the unique key prop error? 是什么导致独特的按键道具错误?


解决方案:

参考一: https://stackoom.com/question/1urlW/了解React-js中数组子项的唯一键
参考二: https://oldbug.net/q/1urlW/Understanding-unique-keys-for-array-children-in-React-js
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!