Ant Design pro Component 【Schema Form - JSON 表单】依赖与顺序加载问题

发布时间 2024-01-08 11:24:34作者: ZJH_BLOGS

记一次项目中遇到的问题,及解决方法.

使用Ant Design pro Component 【Schema Form - JSON 表单】中碰到一个依赖更新 与 首次加载表单数据冲突的问题。

问题是这样的:

表单是通过json配置生成出来的,导入的数据是一次性导入的,但是表单中有配置规则,当依赖项更新时,其对应的子项将会清除。
由于数据是一次性导入的,所以导入后会触发依赖项更新问题,子项就被清除了。

解决方法:

将依赖项提取出来,首次加载完毕后,依次按依赖顺序加载。以下是实现的代码:


// 递归查父
function loadOrder(child: any, parents: any) {
  let order: any = [];
  let stack = [child];

  while (stack.length > 0) {
    let current = stack.pop();
    if (!order.includes(current)) {
      order.push(current);
      if (parents[current]) {
        stack.push(...parents[current]);
      }
    }
  }

  return order;
}

// 配置顺序-
export const setFormFirstValues = ({ components, form, values }: any) => {
  if (!form) {
    return;
  }
  form.setFieldsValue({
    ...values,
  });
  const obj: any = {}; // 依赖子项和父级
  components.forEach((v: any) => {
    const dep = v.properties?.dependence;
    if (dep && dep.type === 'map_props') {
      obj[v.name] = dep.key;
    }
  });
  // 获取依赖的子项
  const children = Object.keys(obj);

  // 已加载的依赖
  const inLoad: any = {};
  const resOrder: string[] = [];
  children.forEach((item) => {
    const order = loadOrder(item, obj);
    for (let i = order.length - 1; i >= 0; i--) {
      if (!inLoad[order[i]]) {
        inLoad[order[i]] = true;
        // console.log(order[i]);
        resOrder.push(order[i]);
      }
    }
    if (!inLoad[item]) {
      // console.log(item);
      resOrder.push(item);
    }
  });
  // 按顺序加载
  resOrder.forEach((name, index) => {
    setTimeout(
      () => {
        form.setFieldValue(name, values[name]);
      },
      (index + 1) * 100,
    );
  });
};