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

React中如何用InertiaJS FormHelper实现PUT请求转POST提交

问题原因

你的写法存在两处错误:

  • 未在提交数据中添加_method: 'put'参数,Laravel依赖该参数将POST请求识别为PUT请求做路由匹配
  • Inertia FormHelper提供的post方法会自动携带初始化时的表单数据,你额外嵌套了一层data字段,导致Laravel接收到的参数结构异常,所以直接获取字段时返回null

解决方案

方案1:直接使用FormHelper自带的put方法(推荐)

无需手动配置_method参数,FormHelper会自动处理方法覆写逻辑:

// 解构时取出put方法
const { data, setData, put, reset, errors, processing, progress } = useForm({
  name: model.name,
  category_id: model.category_id,
  descriptions: model.descriptions,
  bestproduct: model.bestproduct,
  image: null,
});

const submitHandlerType = (event) => {
  event.preventDefault();
  // 直接调用put方法,不需要额外传递data参数
  put(route("products.update", model.id), {
    onSuccess: () => {
      reset(), close();
    },
  });
};

方案2:保留POST提交方式

如果你确实需要用POST请求模拟PUT提交,在表单初始化时添加_method字段,同时去掉提交时的data嵌套:

const { data, setData, post, reset, errors, processing, progress } = useForm({
  _method: 'put', // 新增方法覆写字段
  name: model.name,
  category_id: model.category_id,
  descriptions: model.descriptions,
  bestproduct: model.bestproduct,
  image: null,
});

const submitHandlerType = (event) => {
  event.preventDefault();
  // 调用post方法时不需要传入data字段
  post(route("products.update", model.id), {
    onSuccess: () => {
      reset(), close();
    },
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:45:06