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

React中如何将高尔夫球场18洞表单输入生成的多个对象添加到列表

解决方案

你不需要双层循环,利用JS的方括号动态属性取值+模板字符串拼接属性名就能实现需求,核心逻辑如下:

简化写法(推荐)

const handleSubmit = () => {
  // 直接生成符合后端格式的提交数组
  const submitList = Array.from({length: 18}, (_, idx) => {
    const holeNum = idx + 1
    const currentFormEntry = form[idx]
    return {
      hole: holeNum,
      par: currentFormEntry[`par${holeNum}`],
      stroke: currentFormEntry[`stroke${holeNum}`],
      yards: currentFormEntry[`yards${holeNum}`],
      course: {
        courseid: 3 // 替换为实际的courseid即可
      }
    }
  })
  // 此处直接调用后端接口传递submitList即可
}

适配你原有for循环的写法

const submitList = []
for (let i = 1; i < 19; i++) {
  // form数组下标从0开始,对应1号洞取下标0,以此类推
  const currentFormEntry = form[i - 1]
  submitList.push({
    hole: i,
    par: currentFormEntry[`par${i}`],
    stroke: currentFormEntry[`stroke${i}`],
    yards: currentFormEntry[`yards${i}`],
    course: {
      courseid: 3
    }
  })
}
// 处理完的submitList就是要提交给后端的数组

额外优化建议

你当前的form结构可以进一步简化,不需要给每个字段加数字后缀,直接按如下结构定义,后续表单赋值和提交处理会更方便:

const [form, setForm] = useState(
  Array.from({length:18}, (_, idx) => ({
    hole: idx + 1,
    par: '',
    stroke: '',
    yards: ''
  }))
)

修改对应洞的字段时只需要按索引操作,不需要拼接属性名,提交时也可以直接映射结构,不用处理动态属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:36:05