React18.2+Antd框架实现table控件中多行数据修改


当table控件中有多行数据的时候,点击编辑选择一行数据进行修改
会把这个table中所有的数据都修改了
 const columntwo = [
{
          title: '编辑',
          key: 'edit',
          render: (text, record) => (
            <Button type='primary' onClick={() => handleEdit(record)}>编辑</Button>
          ),
        },
        {
          title: '启用条件',
          dataIndex: 'Enabling',
          key: 'Enabling',
          width: 100,
          render: (_, record) => {
            const enablingValue = enablingValues[record.key];
            
            // 只在字段存在时渲染 EnablingInput 组件
            return enablingValue ? (
              <div style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
                <EnablingInput
                  initialValue={enablingValue}
                  onChange={(value) => handleEnablingChange(record.key, value)}
                />
              </div>
            ) : null;
          },
        },
        ];

 const handleEnablingChange = (key, value) => {
      debugger
      setEnablingValues((prevValues) => ({
        ...prevValues,
        [key]: value,
      }));
    };

      const handleEdit = (record) => {
        setShowModal(true);
        setEditingKey(record.key);
      
       
      };
      
      const onSaven= (values) => {
        debugger
        const { Enabling } = values;
        enablingValues[editingKey] = Enabling;
        const { Available } = values;
        AvailableValues[editingKey] = Available;
        const { editcoding } = values;
        EditcondValues[editingKey] = editcoding;
        const { updatevent } = values;
        updateventValues[editingKey] = updatevent;
        const { filedencoding } = values;
        filedencodingValues[editingKey] = filedencoding;

        // 更新完毕后清空 editingKey

         // 创建副本数组
        const updatedTableData = [...columntwoData[SolutionNo]];

        // 找到要编辑的行在副本数据中的位置
        const index = updatedTableData.findIndex(item => item.key === editingKey);

        // 更新该记录的字段值
        updatedTableData[index] = {
          ...updatedTableData[index],
          enablingValue: Enabling,
          Availablevalue: Available,
          editcodingvalue: editcoding,
          updateventValue: updatevent,
          filedencodingValue: filedencoding,
        };

        // 更新表格数据状态变量的选中行数据
        setColumntwoData({
          ...columntwoData,
          [SolutionNo]: updatedTableData,
        });

        // 清空 editingKey
        setEditingKey(null);
        setShowModal(false);

       
      };


 { columntwoData[SolutionNo] && columntwoData[SolutionNo].length > 0 && (
                console.log('dataSource', columntwoData),
                <Table dataSource={columntwoData[SolutionNo]} columns={columntwo} key={SolutionNo} />
              )}      
        
        
        columntwoData这个数据里面在第二个集合中明明没有 Availablevalue 、enablingValue 但是在table中还是显示出来了
        数据格式如下        
        1:  
            Array(2)
            0: Availablevalue: "2"
            attributes: "DescAttributes"
            editcodingvalue: undefined
            en_name: "EnglishName"
            enablingValue: "1"
            fields: "PushDesc"
            filedencodingValue: undefined
            id: "1ddf65a9-9a56-4fcb-81e1-08db751e91db"
            length: "1000"
            name: "描述"
            table_name: "PushScan"
            type: "nvarchar"
            updateventValue: undefined
            zh_name: "Chinese"
            [[Prototype]]
            : Object
            1: attributes: "DescAttributes"
            en_name: "EnglishName"
            fields: "PushDesc"
            id: "d436a2a9-ad87-4ee9-a510-08db77bbab13"
            length: "1000"
            name: "描述"
            table_name: "PushParent"
            type: "nvarchar"
            zh_name: "Chinese" 

img


如图所示我的第二个数据源明明没有文本框这块的数据,但是在显示的时候还是显示出来了。

img

你的record没有key这个字段,那就是undefined,两个拿的都是undefined对应的enablingValue ,所以显示一样没毛病。

img

【以下回答由 GPT 生成】

问题解答:

问题的根本原因是在 handleEdit 函数中,通过 setEditingKey 设置了当前编辑行的 key,而在 onSave 函数中,却直接通过 editingKey 来修改数据。因此,每次保存时会修改所有行的数据。

要解决这个问题,我们可以对数据进行一次拷贝,然后只修改当前行的数据,而不会影响其他行。

下面是优化后的代码:

import React, { useState, useEffect } from 'react';
import { Table, Button } from 'antd';

const columntwo = [
  {
    title: '编辑',
    key: 'edit',
    render: (text, record) => (
      <Button type='primary' onClick={() => handleEdit(record)}>编辑</Button>
    ),
  },
  {
    title: '启用条件',
    dataIndex: 'Enabling',
    key: 'Enabling',
    width: 100,
    render: (_, record) => {
      const enableValuesCopy = [...enableValues];
      const enablingValue = enableValuesCopy[record.key];

      // 只在字段存在时渲染 EnablingInput 组件
      return enablingValue ? (
        <div style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
          <EnablingInput
            initialValue={enablingValue}
            onChange={(value) => handleEnablingChange(record.key, value)}
          />
        </div>
      ) : null;
    },
  },
];

const MyTable = () => {
  const [enableValues, setEnableValues] = useState([]);
  const [editingKey, setEditingKey] = useState('');

  const handleEdit = (record) => {
    setEditingKey(record.key);
  };

  const handleEnablingChange = (key, value) => {
    const enableValuesCopy = [...enableValues];
    enableValuesCopy[key] = value;
    setEnableValues(enableValuesCopy);
  };

  const onSave = (record) => {
    const enableValuesCopy = [...enableValues];
    enableValuesCopy[editingKey] = record.Enabling;
    setEnableValues(enableValuesCopy);
    setEditingKey('');
    // 其他处理逻辑...
  };

  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      rowKey='key'
      pagination={false}
      scroll={{ y: 400 }}
    />
  );
};

export default MyTable;

经过优化后,我们在修改数据的时候只会影响当前行,而不会影响其他行。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^