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

编辑表单无法预填原有数据且更新请求返回400错误的技术求助

编辑表单无法预填原有数据且更新请求返回400错误的技术求助

我最近在做一个可创建、可编辑的卡片表单功能,碰到了两个棘手的问题:

  1. 点击编辑按钮进入页面时,原有卡片的信息没法自动填充到表单里;
  2. 强行提交更新时,会收到400 (Bad Request)错误,直接被服务器拒绝请求。

我试过把日期格式改成整数、浮点数,也尝试把useParams里的id改成experienceID,结果反而冒出更多错误。我反复检查了GraphQL的mutation、resolver、typeDefs这些核心代码,都没找到问题;甚至找AI帮忙,它建议把所有日期从字符串改成整数,但这并没有解决更新表单的核心问题。

以下是我的ExperiencePage.js代码(粘贴时存在部分截断):

import { useMutation, useQuery } from "@apollo/client";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { GET_EXPERIENCE } from "../graphql/queries/experience.query.js";
import { UPDATE_EXPERIENCE } from "../graphql/mutations/experience.mutations.js";
import toast from "react-hot-toast";

const ExperiencePage = () => {
  const { id } = useParams();
  const { loading, data} = useQuery(GET_EXPERIENCE, {
    variables: { id: id },
  });
  console.log("UseQuery:", data)

  const [updateExperience] = useMutation(UPDATE_EXPERIENCE);

  const [formData, setFormData] = useState({
    description: data?.experience?.description || "",
    title: data?.experience?.title || "",
    type: data?.experience?.type || "",
    startDate: data?.experience?.startDate || "",
    endDate: data?.experience?.endDate || "",
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await updateExperience({
        variables: {
          input: {
            ...formData,
            experienceID: id,
            startDate: formData.startDate ? new Date(formData.startDate).getTime() : null,
            endDate: formData.endDate ? new Date(formData.endDate).getTime() : null,
          },
        },
      });
      toast.success("Experience updated successfully");
    } catch (error) {
      toast.error(error.message || "Update failed");
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
    console.log(formData)
  };

  useEffect(() => {
    if (data && data.experience) {
      setFormData({
        description: data.experience.description || "",
        title: data.experience.title || "",
        type: data.experience.type || "",
        startDate: data.experience.startDate ? new Date(Number(data.experience.startDate)).toISOString().slice(0, 10) : "",
        endDate: data.experience.endDate ? new Date(Number(data.experience.endDate)).toISOString().slice(0, 10) : "",
      });
    }
  }, [data]);

  if (loading) return <p>Loading...</p>

  return (
    <div>
      {/* */}
      <form className="w-full max-w-lg flex flex-col gap-5 px-3" onSubmit={handleSubmit}>
        <div className="space-y-12">
          <div className="border-b border-gray-900/10 pb-12">
            <h2 className="text-base/7 font-semibold text-gray-900">Update Experience Form</h2>
            <div className="mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
              <div className="sm:col-span-4">
                <label htmlFor="title" className="block text-sm/6 font-medium text-gray-900">
                  Title
                </label>
                <div className="mt-2">
                  <div className="flex items-center rounded-md bg-white pl-3 outline-1 -outline-offset-1 outline-gray-300 focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-indigo-600">
                    <input className="block min-w-0 grow py-2 pr-3 pl-1 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-sm/6"
                      id="title"
                      name="title"
                      type="text"
                      placeholder="Title"
                      value={formData.title}
                      onChange={handleInputChange}
                    />
                  </div>
                </div>
              </div>
              <div className="col-span-full">
                <label htmlFor="description" className="block text-sm/6 font-medium text-gray-900">
                  Description
                </label>
                <div className="mt-2">
                  <textarea id="description"
                    name="description"
                    rows={3}
                    className="block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600 sm:text-sm/6"
                    placeholder="Write a description of your experience: Awards, goals achieved, lessons learned, etc. Make sure to use keywords you want to be analyzed."
                    value={formD

我自己梳理了几个排查方向,但还没找到根因:

  • 查看控制台的UseQuery输出,确认GET_EXPERIENCE是否真的返回了完整的experience对象;
  • 检查后端UPDATE_EXPERIENCE的参数要求,确认input里的字段名(比如experienceID)、日期格式是否和后端定义一致;
  • 验证useEffect是否在data加载完成后正确触发,更新了formData;
  • 确认useParams拿到的id是否和后端查询/更新时需要的参数匹配。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 06:59:34