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

API提交时需拆分多选答案数组,保留问题ID关联

解决方案

1. 修复多选值的格式问题

先修正getValue函数,当前返回的二维数组会导致payload出现嵌套结构,直接返回选中值的一维数组即可:

const getValue = (choiceRef) => {
  return choiceRef.filter((i) => i.checked).map((i) => i.value);
};

2. 拆分多选答案并批量提交

在handleSubmit中,将多选答案拆分为单个独立条目,每个条目对应一次API请求,同时保留关联的问卷、问题、用户答卷ID。用Promise.all确保所有提交完成后再执行后续操作:

function handleSubmit(data: any) {
  setLoading(true);

  // 处理答案:拆分多选条目
  const processedAnswers = data.answer.flatMap(answer => {
    const { questionAlternative, ...rest } = answer;
    // 判断是否为多选(id是数组)
    if (Array.isArray(questionAlternative.id)) {
      // 遍历每个选项,生成独立的answer对象
      return questionAlternative.id.map(altId => ({
        ...rest,
        questionAlternative: { id: altId } // 转为单个ID值
      }));
    }
    // 客观题直接返回原对象
    return [answer];
  });

  // 批量提交所有答案
  Promise.all(processedAnswers.map(answer => apiBase.create("answer/all", answer)))
    .then(() => {
      // 更新问卷详情
      if (survey) {
        return apiBase.find<IEventDetailDTO>(
          "event-detail",
          `typeDetail=ID&eventEventTypeId=3&idReference=${survey.id}`,
        ).then(({ data: eventDetails }) => {
          eventDetails[0] && apiBase.patch(
            "event-detail",
            eventDetails[0],
            { dateSurveyAnswered: nowDate() },
            { headers: { noMessage: true } },
          );
        });
      }
    })
    .then(() => {
      // 更新答卷状态
      return apiBase.patch(
        "/person-survey",
        { id: personSurveyId },
        { statusTarget: "RESPONDIDO" },
        { headers: { noMessage: true } },
      );
    })
    .finally(() => {
      setLoading(false);
    });
}

关键说明

  • 用flatMap遍历处理每个答案:如果是多选(questionAlternative.id为数组),则拆分为多个独立的提交对象;客观题直接保留原结构
  • Promise.all保证所有答案提交完成后,再执行后续的问卷详情更新和答卷状态修改
  • 拆分后的每个条目都保留了原有的survey、question、personSurvey关联信息,完全匹配API要求的单个ID格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:02:07