likes
comments
collection
share

[React] Each child in a list should have a unique

作者站长头像
站长
· 阅读数 17

react + ant design使用table时,出现了报错,错误信息如下Each child in a list should have a unique “key“ prop.出现这个问题,table的每一行需要一个"key"。

如果table的 dataSource[i].key 这个属性不存在可以在 Table上添加一个rowKeyrowKey可以是一个字符串,指定dataSource[i]上的一个属性也可以是一个函数,返回dataSource[i]上的一个key

举个例子:

代码来源是ant design官方的table  (ts版本)

https://ant.design/components..."简单的表格,最后一列是各种操作。"

// ↓ 去掉了官方代码中的data[i].key

const data: DataType[] = [
  {
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];

const App: React.FC = () => <Table columns={columns} dataSource={data} />;// ↑ 上面的写法会报错 Each child in a list should have a unique “key“ prop.

// 改1、const App: React.FC = () =>

<Table columns={columns} dataSource={data} rowKey={"name"} />;

// 或者2、const App: React.FC = () =>

<Table columns={columns} dataSource={data} rowKey={item => item.name} />;

同步更新到自己的语雀https://www.yuque.com/diracke...