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

如何统计Formik嵌套FieldArray中childrenLevel的总错误数?

统计Formik嵌套FieldArray内的总错误数

针对你这种嵌套FieldArray的错误统计需求,直接遍历Formik返回的errors对象即可,以下是具体实现方法:

实现函数

根据你的错误结构,提供两种统计逻辑的函数:

// 统计所有字段级错误总数(比如每个未填的name/age各算一个错误)
const countChildrenFieldErrors = (errors) => {
  let total = 0;
  if (!errors.parentLevel || !Array.isArray(errors.parentLevel)) return total;

  errors.parentLevel.forEach(parent => {
    if (!parent.childrenLevel || !Array.isArray(parent.childrenLevel)) return;
    parent.childrenLevel.forEach(child => {
      total += Object.keys(child || {}).length;
    });
  });
  return total;
};

// 统计「有错误的子项数量」(匹配你例子里期望的2个结果)
const countErrorChildItems = (errors) => {
  let total = 0;
  if (!errors.parentLevel || !Array.isArray(errors.parentLevel)) return total;

  errors.parentLevel.forEach(parent => {
    if (!parent.childrenLevel || !Array.isArray(parent.childrenLevel)) return;
    parent.childrenLevel.forEach(child => {
      if (Object.keys(child || {}).length > 0) total += 1;
    });
  });
  return total;
};

组件内使用

在Formik包裹的组件中,通过useFormikContext获取错误对象后调用函数即可:

import { useFormikContext } from 'formik';

// 组件内部逻辑
const { errors } = useFormikContext();
const fieldErrorCount = countChildrenFieldErrors(errors);
const itemErrorCount = countErrorChildItems(errors);

// 页面展示
return (
  <div>
    <p>字段级错误总数:{fieldErrorCount} errors</p>
    <p>有错误的子项数量:{itemErrorCount} errors</p>
  </div>
);

逻辑说明

  • 先判断目标数组是否存在,避免undefined或非数组类型导致遍历报错
  • 第一层遍历parentLevel数组,第二层遍历每个父项对应的childrenLevel数组
  • 对每个子项,通过Object.keys(child).length获取当前子项的错误字段数:
    • 统计字段级错误时直接累加该数值
    • 统计有错误的子项数量时,判断该数值是否大于0,是则计数加1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:50:18