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

React使用json-server向指定日期的exercises数组添加锻炼项目的问题

解决方案

错误原因

你当前使用POST请求调用/dates接口的逻辑本身不符合json-server的接口规则:
POST请求作用于顶层资源路径(如/dates)时,默认行为始终是新增一条顶层资源条目,URL携带的?id=xxx只是查询筛选参数,不会改变POST的新增逻辑,因此会出现你遇到的、新锻炼项目被当成新date条目插入的问题。

正确实现方式

你需要使用PATCH请求修改指定ID的日期条目,局部更新其下的exercises数组即可,无需修改json-server的默认配置,完整代码如下:

// 替换为你要新增锻炼的日期ID
const targetDateId = ID;
// 1. 先获取指定日期的现有数据
const targetDateRes = await fetch(`http://localhost:8000/dates/${targetDateId}`);
const targetDate = await targetDateRes.json();
// 2. 给新锻炼生成唯一ID,避免和已有锻炼ID冲突
const newExerciseId = targetDate.exercises.length 
  ? Math.max(...targetDate.exercises.map(item => item.id)) + 1
  : 0;
const newExercise = {
  ...exercise,
  id: newExerciseId
};
// 3. 发送PATCH请求,只更新对应日期的exercises数组
await fetch(`http://localhost:8000/dates/${targetDateId}`, {
  method: "PATCH",
  headers: {
    "Content-type": "application/json",
  },
  body: JSON.stringify({
    exercises: [...targetDate.exercises, newExercise]
  }),
});

逻辑说明

PATCH是json-server提供的局部更新接口,调用时直接指向要修改的资源路径/dates/[日期ID],提交的内容只会覆盖你传入的字段,不会修改日期条目的其他属性,完全满足你给指定日期新增锻炼项目的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:18:01