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

如何在React Syncfusion Grid中更新本地JSON文件

需求与解决方案

需求概述

基于本地JSON文件构建Syncfusion React Grid组件,要求在Grid中执行添加、编辑、删除行数据操作时,同步更新本地JSON文件。

核心限制说明

浏览器出于安全机制,无法直接修改本地文件,因此需根据场景选择合适的实现方案:


方案1:后端接口处理(生产环境推荐)

通过Node.js后端编写接口,接收Grid的变更数据并写入本地JSON文件,前端调用接口完成同步。

步骤1:搭建Node.js后端服务

创建Express服务器,提供数据读取与写入接口:

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.use(express.json());

// 获取数据接口
app.get('/api/data', (req, res) => {
  const dataPath = path.join(__dirname, 'data.json');
  fs.readFile(dataPath, 'utf8', (err, data) => {
    if (err) return res.status(500).json({ error: '读取文件失败' });
    res.json(JSON.parse(data));
  });
});

// 写入数据接口
app.post('/api/data', (req, res) => {
  const updatedData = req.body;
  const dataPath = path.join(__dirname, 'data.json');
  fs.writeFile(dataPath, JSON.stringify(updatedData, null, 2), 'utf8', (err) => {
    if (err) return res.status(500).json({ error: '写入文件失败' });
    res.json({ success: true });
  });
});

app.listen(3001, () => console.log('服务器运行于 http://localhost:3001'));

步骤2:修改React Grid组件

利用Syncfusion Grid的actionComplete事件监听数据变更,调用后端接口同步数据:

import React, { useState, useEffect } from "react";
import { GridComponent, ColumnsDirective, ColumnDirective } from "@syncfusion/ej2-react-grids";
import { Edit, Inject, Toolbar, Page, Group, Print } from "@syncfusion/ej2-react-grids";

import { Header } from "../../components";
import { useStateContext } from "../../contexts/ContextProvider";

const Grid = () => {
  const { currentMode } = useStateContext();
  const toolbarOptions = ["Add", "Edit", "Delete", "Update", "Cancel", "Search", "Print"];
  const editOptions = {
    allowEditing: true,
    allowAdding: true,
    allowDeleting: true,
    mode: "Normal",
  };

  const [gridData, setGridData] = useState([]);

  // 从后端获取初始数据
  const fetchData = () => {
    fetch("http://localhost:3001/api/data")
      .then(res => res.json())
      .then(data => setGridData(data))
      .catch(err => console.error('数据获取失败:', err));
  };

  // 同步数据到后端
  const syncData = (updatedData) => {
    fetch("http://localhost:3001/api/data", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(updatedData)
    })
    .then(res => res.json())
    .then(result => result.success && console.log('数据同步成功'))
    .catch(err => console.error('数据同步失败:', err));
  };

  // 监听Grid操作完成事件
  const handleActionComplete = (args) => {
    if (args.requestType === "save" || args.requestType === "delete") {
      const updatedData = args.grid.dataSource;
      setGridData([...updatedData]);
      syncData(updatedData);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div style={{ margin: "3%", marginTop: "5%", marginBottom: "5%" }}>
      <Header category='Grid' title='' />

      <GridComponent
        dataSource={gridData}
        toolbar={toolbarOptions}
        allowPaging={true}
        editSettings={editOptions}
        pageSettings={{ pageSize: 10 }}
        allowGrouping={true}
        height={265}
        background={currentMode === "Dark" ? "#33373E" : "#fff"}
        actionComplete={handleActionComplete}
      >
        <ColumnsDirective>
          <ColumnDirective
            field='Short_Name'
            headerText='Short Name'
            textAlign='Center'
            width='100'
            isPrimaryKey={true} // 设置主键,确保Grid正确识别唯一行
          />
          <ColumnDirective field='Name' headerText='Name' textAlign='Right' width='100' />
          <ColumnDirective
            field='Description'
            headerText='Description'
            textAlign='Right'
            width='100'
          />
          <ColumnDirective field='Type' headerText='Type' textAlign='Right' width='100' />
        </ColumnsDirective>
        <Inject services={[Page, Group, Edit, Toolbar, Print]} />
      </GridComponent>
    </div>
  );
};

export default Grid;

方案2:纯前端下载实现(无后端场景)

无法自动修改本地文件,仅能通过生成新JSON文件并触发下载,由用户手动替换原文件:

修改Grid组件添加下载逻辑

// ... 其他代码保持不变

// 生成并下载更新后的JSON文件
const downloadUpdatedJson = (data) => {
  const jsonContent = JSON.stringify(data, null, 2);
  const blob = new Blob([jsonContent], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const downloadLink = document.createElement("a");
  
  downloadLink.href = url;
  downloadLink.download = "data.json";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(url);
};

// 监听Grid操作完成事件
const handleActionComplete = (args) => {
  if (args.requestType === "save" || args.requestType === "delete") {
    const updatedData = args.grid.dataSource;
    setGridData([...updatedData]);
    downloadUpdatedJson(updatedData);
    alert("数据已更新,请将下载的data.json替换原文件");
  }
};

// ... 其他代码保持不变

关键注意点

  • 必须为Grid的某一列设置isPrimaryKey={true},确保Syncfusion能正确处理行数据的增删改操作。
  • actionComplete事件是监听Grid数据变更的核心入口,通过args.requestType可判断具体操作类型。

内容的提问来源于stack exchange,提问作者Akkipeddi Sudhakar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:54:55