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

如何转换适配Ant Design Tree组件的多层嵌套数据?

解决Ant Design Tree多层嵌套数据适配问题

核心解决方案:递归转换函数

写一个递归函数,遍历每一层节点,将服务器返回的结构转换成Tree组件需要的title/key/children格式,自动处理任意层级的子节点:

// 递归转换单个节点为Tree格式
const transformToTreeData = (node) => {
  if (!node) return null;
  
  // 基础转换:提取title和key
  const treeNode = {
    title: node.title,
    key: node.id,
  };
  
  // 处理子节点:如果存在子节点且是数组,递归转换
  if (Array.isArray(node.childs) && node.childs.length > 0) {
    treeNode.children = node.childs.map(child => transformToTreeData(child));
  }
  
  return treeNode;
};

// 生成最终的treeData
const treeData = chart ? [transformToTreeData(chart)] : [];

解决你遇到的两个问题

  1. "data.foreach is not a function"错误

    • 大概率是你误写了forEach的大小写(正确写法是大写E:forEach),或者childs不是数组(比如服务器返回null/undefined)。上面的函数用Array.isArray(node.childs)先判断类型,避免非数组调用map/forEach的错误。
  2. 无法处理多层嵌套

    • 之前的代码只转换了第一层子节点,没有递归处理子节点的子节点。递归函数会自动遍历每一层,不管是4层还是更多层级都能适配。

替代方案:循环实现(避免深层级栈溢出)

如果你的数据层级极深(超过1000层),递归可能导致栈溢出,可以用循环+栈的方式实现:

const transformToTreeData = (rootNode) => {
  if (!rootNode) return null;
  
  // 复制根节点,避免修改原数据
  const treeRoot = { title: rootNode.title, key: rootNode.id };
  // 用栈存储待处理的节点对(Tree节点 + 原数据节点)
  const stack = [[treeRoot, rootNode]];
  
  while (stack.length > 0) {
    const [currentTreeNode, currentDataNode] = stack.pop();
    
    if (Array.isArray(currentDataNode.childs) && currentDataNode.childs.length > 0) {
      currentTreeNode.children = currentDataNode.childs.map(child => ({
        title: child.title,
        key: child.id,
      }));
      
      // 将子节点对推入栈,继续处理
      currentTreeNode.children.forEach((treeChild, index) => {
        stack.push([treeChild, currentDataNode.childs[index]]);
      });
    }
  }
  
  return treeRoot;
};

const treeData = chart ? [transformToTreeData(chart)] : [];

注意事项

  • 确保服务器返回的每个节点都有title和id字段,如果字段名不同,直接修改函数里的对应字段即可(比如把node.id改成node.nodeId)。
  • 如果子节点字段名不是childs,改成你实际的字段名(比如children)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:42:22