You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在编辑MUI的DataGrid行数据后同步更新Firebase数据

解决方案

1. 非Pro版MUI DataGrid编辑模式配置

免费版DataGrid不需要依赖Pro套件,两步即可开启编辑能力:

  • 给需要支持编辑的列添加editable: true属性
  • 给DataGrid组件配置编辑模式和更新回调,用来获取编辑后的值

2. 编辑状态存储逻辑

用本地状态暂存所有修改过的行数据,批量提交时直接读取即可:

// 新增状态存储编辑后的行数据,key为行id,value为修改后的完整行对象
const [editedRows, setEditedRows] = useState({});

3. DataGrid组件完整配置

<DataGrid
  rows={estudiantes}
  columns={columns}
  checkboxSelection
  selectionModel={selectionModel}
  onSelectionModelChange={setSelectionModel}
  // 编辑模式配置,可选'row'(整行编辑)或'cell'(单格编辑)
  editMode="row"
  // 编辑完成触发的回调,拿到旧行和新行数据
  processRowUpdate={(newRow, oldRow) => {
    setEditedRows(prev => ({
      ...prev,
      [oldRow.id]: newRow
    }))
    // 必须返回新行,否则DataGrid视图不会更新
    return newRow
  }}
  onProcessRowUpdateError={(err) => console.error('编辑失败:', err)}
/>

4. 批量提交按钮逻辑修改

直接从暂存的editedRows中读取修改后的值提交到Firebase即可,修改后的列配置如下:

const columns = [
  // 其他需要展示/编辑的列
  { field: 'nombre', headerName: '姓名', editable: true, width: 150 },
  { field: 'colegio', headerName: '学校', editable: true, width: 150 },
  { field: 'grado', headerName: '年级', editable: true, width: 100 },
  // 原有批量提交按钮列
  {
    field: "edit", 
    width: 70, 
    sortable: false, 
    disableColumnMenu: true,
    renderHeader: () => {
      return (
        <IconButton
          onClick={async () => {
            const selectedIDs = new Set(selectionModel);
            try {
              for (const x of estudiantes.filter(item => selectedIDs.has(item.id))) {
                // 优先取编辑后的值,未编辑则取原始值
                const targetData = editedRows[x.id] || x;
                const temporalQuery = db.collection("usuarios").doc(user.uid).collection("estudiantes").doc(x.uid);
                await temporalQuery.update({
                  nombre: targetData.nombre,
                  colegio: targetData.colegio,
                  grado: targetData.grado
                })
              }
              // 提交成功后清空编辑缓存
              setEditedRows({})
              alert('数据更新成功')
            } catch (err) {
              console.error('提交失败:', err)
              alert('数据更新失败,请重试')
            }
          }}
        >
          <EditSharpIcon />
        </IconButton>
      );
    }
  }
]

可选优化

如果不需要批量提交,想编辑完成后立刻自动同步到Firebase,直接在processRowUpdate回调中调用Firebase更新逻辑即可,无需额外存储editedRows状态。

内容的提问来源于stack exchange,提问作者React Enjoyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:09:03