antd Table rowkey 未设导致 antd 组件 swtich 渲染状态错误

276 阅读1分钟

antd switch 组件 table 表格渲染错误

目前项目中碰到的问题 Table 未设 rowkey, 使用了 默认的 rowkey, 会导致 swtich 状态框渲染问题 重现步骤:

  • 使用搜索框搜索,
  • 剔除搜索条件
  • swtich 状态错乱

解决方法:

注意: 需要设置 rowKey 为表格数据的唯一数据属性

原因分析

rowkey 未设置的情况下默认为 key, 若数据源属性未含 key, 会导致 react 这边 diff 算法认为是同一个,而导致渲染出错

表格列背景色重置

render(text, record) {
          return {
            props: {
              style: { background: parseInt(text) > 50 ? "red" : "green" }
            },
            children: <div>{text}</div>
          };
        }

表格行合并重写 onCell 函数

  onCell: onCell,
  
  const onCell = (
    record:
      | ColumnGroupType<RateLimitTableItem>
      | ColumnType<RateLimitTableItem>,
    index: number | undefined,
  ) => ({
    rowSpan: record?.rowSpan || 0,
  });