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

如何在Axios自动保存POST请求前检查表单是否含标题及章节

解决方案

你可以在发起Axios POST请求前,先对title、section、subsection做存在性校验,确保这三个字段都有有效内容后再执行后续请求逻辑。以下是修改后的代码:

const onClickADD = () => {
    setLoader(true);
    
    // 检查title、section、subsection是否存在(排除空字符串、纯空格情况)
    if (!title?.trim() || !section?.trim() || !subsection?.trim()) {
        setLoader(false);
        // 可替换为你项目中使用的提示组件,比如UI库的错误提示
        alert('title、section、subsection不能为空,请完善后再保存');
        return;
    }

    apiService
      .post(`${APP_URL}/performance-review/questions/`, {
        title: title,
        question: quest,
        is_text: isText,
        is_hr_question: false,
        is_employee_question: false,
        is_client_question: false,
        is_team_lead_question: false,
        // 如果POST接口需要接收section和subsection,解开下面的注释并添加参数
        // section: section,
        // subsection: subsection
      })
      .then(async () => {
        const result = await apiService.get(
          `${APP_URL}/performance-review/questions/`
        );
        var lastId = result[result.length - 1].id;
        let patchData = {
          id: param2.formId,
          add_questions: [lastId],
        };
        return apiService.patch(`${APP_URL}/performance-review/pr-form/`, patchData);
      })
      .then(() => {
        setQuestionForms();
        setTrigerChanges(true);
        setOpenAddModal(false);
      })
      .catch((error) => {
        console.error('保存操作失败:', error);
        // 这里可添加错误提示逻辑
      })
      .finally(() => {
        // 无论请求成功或失败,都关闭加载状态
        setLoader(false);
      });
  };

关键说明:

  • 使用?.trim()是为了过滤掉纯空格的无效输入,确保用户填写了实际内容。
  • 校验不通过时会立即关闭加载状态、提示用户,并终止后续请求流程。
  • 若接口需要接收section和subsection参数,记得在POST请求体中添加对应字段(代码中已给出注释提示)。
  • 补充了catch和finally块,处理请求异常并保证加载状态最终被关闭,避免页面一直处于加载状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:25:19