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

React+Axios场景下如何校验数据库中是否已存在重复的名称?

实现方案

第一步:调整分类列表数据存储逻辑

你当前的categList存储的是名称+描述拼接的字符串,无法单独提取名称做匹配,需要额外存储所有已存在的分类名称集合:

// 新增state存储所有已存在的分类名称
const [existingNames, setExistingNames] = useState([]);
const [categList, setCategList] = useState([]);

const getItems = () => {
  Axios.get(url).then((response) => {
    // 提取所有分类名称,提前做trim处理避免空格导致的匹配误差
    const names = response.data.map(item => item.name.trim());
    setExistingNames(names);
    
    // 保留原有的分类列表渲染逻辑
    const categories = response.data.map((resCateg) => {
      return resCateg.name + ", " + resCateg.description;
    });
    setCategList(categories);
  });
};

第二步:在提交逻辑中添加唯一性校验

在e.preventDefault()之后添加校验逻辑,匹配到重复名称直接终止提交:

function submit(e) {
  e.preventDefault();
  resetFormValidationErrors();

  // 新增名称唯一性校验
  const inputName = data.name.trim();
  // 如果需要忽略大小写校验,可改为 existingNames.map(n => n.toLowerCase()).includes(inputName.toLowerCase())
  if (existingNames.includes(inputName)) {
    // 替换为你项目中的表单错误提示逻辑即可
    setFormValidationErrors({ name: "该分类名称已存在,请更换后重试" });
    // 终止后续提交流程
    return;
  }

  Axios.post(url, {
    name: data.name,
    description: data.description,
  }).then((res) => {
    resetForm();
    // 提交成功后更新已存在名称集合,避免下一次提交相同名称时校验失效
    setExistingNames(prev => [...prev, inputName]);
  });
}

注意事项

  • 前端校验仅用于优化用户体验,必须在后端也做名称唯一性校验,同时给数据库对应表的name字段添加唯一索引,防止绕开前端的请求插入重复数据
  • 如果分类数据量级很大(万条以上),不建议一次性拉取全量名称到前端校验,可以改为提交前单独调用后端校验接口,传入当前输入的名称查询是否存在
  • 如果后续要支持编辑分类的场景,校验时需要排除当前正在编辑的条目自身的名称,避免把自身判定为重复

内容的提问来源于stack exchange,提问作者Miloš Milutinov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:15:05