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

Next.js+TypeScript+GraphQL开发:警告与本地JSON未更新问题

问题解决:Next.js + Apollo Server 操作本地JSON文件的两个问题

问题1:"Extra attributes from the server: fdprocessedid at input" 警告

原因

该警告源于React hydration过程中服务端与客户端DOM属性不匹配。你的TextField组件未显式设置id,MUI会自动生成随机ID(如fdprocessedid),但服务端和客户端生成的ID不一致,触发React的 hydration 警告。

解决方案

为每个TextField添加与对应InputLabel的htmlFor匹配的id属性:

// 第一个TextField
<TextField
  className='name'
  id="firstName" // 与InputLabel的htmlFor值对应
  name='name'
  value={name}
  type='text'
  onChange={(e) => setName(e.target.value)}
/>

// 第二个TextField
<TextField
  className='email'
  id="email" // 与InputLabel的htmlFor值对应
  name='email'
  value={email}
  type='text'
  onChange={(e) => setEmail(e.target.value)}
/>

问题2:控制台提示数据添加成功,但本地JSON文件未更新

原因

当前createUser resolver仅在内存中生成新用户对象,未对本地JSON文件执行读写操作,数据无法持久化到磁盘。

解决方案

修改resolver,实现读取JSON文件、添加新用户、写入文件的完整逻辑:

首先在resolver.ts中导入必要模块并定义文件路径:

import fs from 'fs/promises';
import path from 'path';

// 替换为你的JSON文件实际路径(相对于项目根目录)
const usersFilePath = path.join(process.cwd(), 'data/users.json');

然后更新createUser resolver:

Mutation: {
  createUser: async (_parent: null, { input }: { input: AddUserInput }): Promise<User> => {
    // 1. 读取现有用户数据
    const fileContent = await fs.readFile(usersFilePath, 'utf8');
    const users: User[] = JSON.parse(fileContent);

    // 2. 生成新用户ID(基于现有最大ID)
    const maxId = users.length ? Math.max(...users.map(u => parseInt(u.id))) : 0;
    const newUserId = maxId + 1;

    // 3. 创建新用户
    const newUser: User = {
      id: newUserId.toString(),
      name: input.name,
      email: input.email,
    };

    // 4. 更新并写入文件
    users.push(newUser);
    await fs.writeFile(usersFilePath, JSON.stringify(users, null, 2));

    return newUser;
  }
}

注意事项

  • 确保文件路径正确,Next.js中使用process.cwd()获取项目根目录。
  • 该逻辑需在服务端环境执行(如API路由、Server Components),避免在客户端组件中直接操作文件。
  • 异步文件操作更适合服务端场景,避免阻塞事件循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:56:02