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

Next.js 14:如何将外键与formData一起传递给Server Action?

如何将cookId传递到Next.js Server Action关联食谱与厨师

有几种简洁的实现方案,以下是具体操作:

方案一:使用隐藏输入字段

在表单中添加一个隐藏输入框,将cookId作为值传入,提交表单时formData会自动携带该字段:

修改new-recipe-form.tsx的表单代码:

<form
  className={classes.form}
  action={formAction}
>
  {/* 新增隐藏字段传递cookId */}
  <input type="hidden" name="cookId" value={cookId} />
  <p>
    <label htmlFor="title">Title</label>
    <input type="text" id="title" name="title" required />
  </p>
  <ButtonSubmit>
    Create Recipe
  </ButtonSubmit>
</form>

在Server Action中从formData提取cookId:

'use server';

export async function newRecipe(previousData, formData){
  const recipe = {
    title: formData.get('title'),
    cookId: formData.get('cookId'), // 获取传递的cookId
  }

  // Zod验证逻辑(建议添加对cookId格式的校验)
  // Prisma入库逻辑示例:
  // await prisma.recipe.create({
  //   data: {
  //     title: recipe.title,
  //     cook: { connect: { id: recipe.cookId } }
  //   }
  // });
}

方案二:绑定参数到Server Action

利用函数绑定,将cookId预先传入Server Action,无需修改表单结构:

修改new-recipe-form.tsx中formAction的创建逻辑:

const [state, formAction] = useFormState(
  (prevData, formData) => newRecipe(prevData, formData, cookId),
  { message: ""}
);

更新Server Action的参数列表,直接接收cookId:

'use server';

export async function newRecipe(previousData, formData, cookId: string){
  const recipe = {
    title: formData.get('title'),
    cookId: cookId,
  }

  // 验证与入库逻辑
}

方案三:手动向formData添加字段(适合动态场景)

通过表单的onSubmit事件,手动将cookId追加到formData中:

const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  const formData = new FormData(e.currentTarget);
  formData.append('cookId', cookId);
  await formAction(state, formData);
};

// 表单部分修改为:
<form
  className={classes.form}
  onSubmit={handleSubmit}
>
  <p>
    <label htmlFor="title">Title</label>
    <input type="text" id="title" name="title" required />
  </p>
  <ButtonSubmit>
    Create Recipe
  </ButtonSubmit>
</form>

注意事项

  • 无论采用哪种方案,都要在Server Action中对cookId做格式验证(比如用Zod校验是否为有效UUID),避免无效数据入库。
  • 若cookId涉及权限控制,需在Server Action中添加校验逻辑,确保当前用户有权创建关联该厨师的食谱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:31:14