React将数据转化成树形结构
本文最后更新于 468 天前,其中的信息可能已经有所发展或是发生改变。

1、React将数据转化成树形结构


// 初始数据
let result = [
  { parentId: null, id: 1, name: "书籍", count: 100 },
  { parentId: 1, id: 2, name: "西游记", count: 50 },
  { parentId: 1, id: 3, name: "红楼梦", count: 10 },
  { parentId: 1, id: 4, name: "水浒传", count: 20 },
  { parentId: 1, id: 5, name: "三国演义", count: 20 },
  { parentId: null, id: 6, name: "文具", count: 10 },
  { parentId: 6, id: 7, name: "铅笔", count: 5 },
  { parentId: 6, id: 8, name: "橡皮", count: 5 },
];

const getTreeData = (treeData, parentId) => {
  // 把数据转化为树型结构
  let tree = [];
  let currentParentId = parentId || null;
  for (let i = 0; i < treeData.length; i += 1) {
    if (treeData[i]) {
      if (treeData[i].parentId === currentParentId) {
        tree.push(treeData[i]);
      }
    }
  }
  for (let j = 0; j < tree.length; j += 1) {
    if (tree[j]) {
      let children = getTreeData(treeData, tree[j].id);
      if (children && children.length) {
        tree[j].children = children;
      }
    }
  }
  return tree;
};

// 树形数据
let data = getTreeData(result);
console.log(data);
/*[
    {
        parentId: null,
        id:1,
        name:'书籍',
        count:100,
        children:[
            {parentId:1,id:2,name:'西游记',count: 50},
            {parentId:1,id:3,name:'红楼梦',count: 10},
            {parentId:1,id:4,name:'水浒传',count: 20},
            {parentId:1,id:5,name:'三国演义',count: 20},
        ]
    },
    {
        parentId: null,
        id:6,
        name:'文具',
        count:10,
        children:[
            {parentId:6,id:7,name:'铅笔',count:5},
            {parentId:6,id:8,name:'橡皮',count:5},
        ]
    }
]*/

2、实例(react antd table树形数据)

线上地址:react antd table 树形结构数据


import React, { useState, useEffect } from 'react';
import { Table } from 'antd';

const Test = () => {
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const columns = [
    {
      title: '名称',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '描述',
      key: 'desc',
      dataIndex: 'desc',
    },
  ];
  const onExpandTable = (expanded, record) => {
    let arr = expandedRowKeys;
    if (expanded) {
      arr.push(record.id);
    } else {
      arr.splice(
        arr.findIndex((i) => i === record.id),
        1
      );
    }
    setExpandedRowKeys(arr);
  };

  const getTreeData = (treeData, parentId) => {
    // 把数据转化为树型结构
    let tree = [];
    let currentParentId = parentId || null;
    for (let i = 0; i < treeData.length; i += 1) {
      if (treeData[i]) {
        if (treeData[i].parentId === currentParentId) {
          tree.push(treeData[i]);
        }
      }
    }
    for (let j = 0; j < tree.length; j += 1) {
      if (tree[j]) {
        let children = getTreeData(treeData, tree[j].id);
        if (children && children.length) {
          tree[j].children = children;
        }
      }
    }
    return tree;
  };

  useEffect(() => {
    const res = [
      {
        parentId: null,
        id: '0e02f058-65fc-4e47-82d5-3aaf95f816cd',
        name: '中国',
        desc: '中国陆地面积约9600000平方千米',
      },
      {
        parentId: '0e02f058-65fc-4e47-82d5-3aaf95f816cd',
        id: '03014a12-3948-4f8a-b182-ed8b6d58a7ea',
        name: '四川',
        desc: '四川地域面积约486000平方公里',
      },
      {
        parentId: '0e02f058-65fc-4e47-82d5-3aaf95f816cd',
        id: '201f9c09-f2e8-4bea-917e-b5fdc56d9e24',
        name: '山东',
        desc: '陆域面积约155800平方公里',
      },
      {
        parentId: '03014a12-3948-4f8a-b182-ed8b6d58a7ea',
        id: '305d7648-9e3e-4b25-a246-3be08344434e',
        name: '成都',
        desc: '成都地域面积约14335平方公里',
      },
      {
        parentId: '201f9c09-f2e8-4bea-917e-b5fdc56d9e24',
        id: '3898961f-7487-46d6-8595-f2dfac59b116',
        name: '济南',
        desc: '济南地域面积约10244.45平方公里',
      },
    ];
    let data = getTreeData(res);
    console.log('data: ', data);
    setDataSource(data);
  }, []);
  return (
    <>
      <Table
        columns={columns}
        dataSource={dataSource}
        rowKey={(record) => record.id}
        expandedRowKeys={expandedRowKeys}
        onExpand={onExpandTable}
        pagination={false}
      />
    </>
  );
};

export default Test;
本文链接:https://likepoems.com/articles/react-tree-structure-data/
转载说明:本站文章若无特别说明,皆为原创,转载请注明来源:likepoems,谢谢!^^

评论

  1. Windows Chrome
    12 月前
    2023-10-26 13:30:34

    感谢分享

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇