如何在react中迭代渲染分层无限深度树结构

问题描述 投票:0回答:0

我已经创建了一个分层树结构,并希望以两种方式呈现它:递归和迭代。该结构可以有无限数量的孩子。我已经设法递归地呈现该结构,但是,我似乎无法解决如何迭代地完成它。

这是我的结构:

  const nodes = [
    {
      name: "node 1",
      children: [
        {
          name: "node 1-1",
          children: [
            {
              name: "node 1-1-1",
              children: [
                {
                  name: "node 1-1-1-1",
                  children: [],
                },
                {
                  name: "node 1-1-1-2",
                  children: [],
                },
              ],
            },
            { name: "node 1-1-2", children: [] },
          ],
        },
        {
          name: "node 1-2",
          children: [],
        },
        {
          name: "node 1-3",
          children: [],
        },
      ],
    },
    {
      name: "node 2",
      children: [],
    },
  ];

我为递归解决方案编写的代码:

  const getTreeRecursively = (nodes: any) =>
    nodes?.map((node: any) => {
      if (node.children?.length === 0) {
        return (
          <div
            style={{
              textAlign: "left",
              marginLeft: "15px",
            }}
          >
            <div>***{node.name}</div>
          </div>
        );
      }
      return (
        <div
          style={{
            textAlign: "left",
            marginLeft: "15px",
          }}
        >
          <div>***{node.name}</div>
          {getTreeRecursively(node.children)}
        </div>
      );
    });

  return <>{getTreeRecursively(nodes)}</>;

这是它的样子:
Example how structure is rendered

现在关于迭代解决方案,我研究了互联网并找到了一个扁平数组的解决方案。然而,这个解决方案并不能使我渲染结构,而只是将平面数组重新排列成与递归解决方案相同的结构。在想也许平面结构可以以某种方式在反应中呈现。

  const flat = [
    { id: 1, parentId: 3 },
    { id: 3, parentId: 8 },
    { id: 4, parentId: 6 },
    { id: 6, parentId: 3 },
    { id: 7, parentId: 6 },
    { id: 8, parentId: null },
    { id: 16, parentId: null },
    { id: 10, parentId: 8 },
    { id: 15, parentId: 8 },
    { id: 13, parentId: 14 },
    { id: 14, parentId: 10 },
  ];

  const root = [];

  flat.forEach((node: any) => {
    if (!node.parentId) {
      return root.push(node);
    }

    const parentIndex = flat.findIndex((el: any) => el.id === node.parentId);
    if (!flat[parentIndex].children) {
      return (flat[parentIndex].children = [node]);
    }

    return flat[parentIndex].children.push(node);
  });

  console.log(root);

image of the console logged root

尝试递归解决方案并成功,但是无法设法迭代地渲染具有无限深度的层次树。

reactjs recursion tree iteration hierarchy
© www.soinside.com 2019 - 2024. All rights reserved.