一、列数据columns里面key
key是列的主键,不同列可以有相同的key,或者不设置也可以,但是如果多行的dataIndex相同的话,列的key就应该不同以区分不同列。
key Unique key of this column, you can ignore this prop if you’ve set a unique dataIndex string -
对列数据,基本没啥疑问。
二、行数据里面的dataSource和rowKey
1、问题
web控制台报错提示如下,虽然暂时不影响网页运行,但还是希望能处理下。
react_devtools_backend.js:4045 Warning: Each record in table shouldhave a unique
key
prop ,or setrowKey
to an unique primary key.
react_devtools_backend.js:4045 Warning: [antd: Table] Each record in dataSource of table should have a uniquekey
prop, or setrowKey
of Table to an unique primary key, see https://u.ant.design/table-row-key
2、 错误理解
rowKey相当于行的主键,不同行不可以有相同的rowKey,有的话虽然行数据会渲染,但是所有rowKey相同的行都会自动高亮。
官网解释如下:
rowKey Row’s unique key, could be a string or function that returns a string string|Function(record):string key
rowKey 表格行 key 的取值,可以是字符串或一个函数 string | function(record): string key
以上造成错误理解:
dataSource里面最好要有key字段。但如果dataSource没有key字段,那就可以使用rowKey来代替,于是想着给rowKey配置一个唯一值,例如:import{ v4 as uuidv4 } from’uuid’; rowKey={uuidv4()} 。 肯定还是有问题了。
3、正确理解
使用rowKey和dataSource配置,这2个必须对应关联的。
rowKey必须设置,可以是固定的,例如rowKey={‘id’}。 但不能非固定的,例如rowKey={uuid4{}}。
如果rowKey={‘id’} ,则dataSource数据都必须有不同的id字段。
如果rowKey={‘key’} ,则dataSource数据都必须有不同的key字段。
解决方式1:让后端给的dataSource包含id字段。
解决方式2:前端自己给dataSource增加id字段。以下是示例代码:
rowKey={'id'}
for(let i=0; i<dataSource.length; i++){
// dataSource[i].key = i.toString()
dataSource[i].id = i.toString()
}