antd报错“should have a unique key prop“的解决思路

本文解析了表格组件中rowKey的正确用法,强调了每行数据需有唯一标识。通过实例说明了rowKey与dataSource的关系,提供了解决方案:确保dataSource有唯一标识或设置rowKey为固定属性。
摘要由CSDN通过智能技术生成

一、列数据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 set rowKey to an unique primary key.
react_devtools_backend.js:4045 Warning: [antd: Table] Each record in dataSource of table should have a unique key prop, or set rowKey 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()
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值