通过map解决导航路由递归问题

1,512 阅读1分钟

问题描述

如何将对象树转换为路由导航,如下图所示 在这里插入图片描述

数据源

const menuList = [
    {
        title: '首页', // 菜单标题名称
        key: '/home', // 对应的path
        icon: <HomeOutlined />, // 图标名称
    },
    {
        title: '商品',
        key: '/products',
        icon: <AppstoreOutlined />,
        children: [ // 子菜单列表
            {
                title: '品类管理',
                key: '/category',
                icon: <DatabaseOutlined />
            },
            {
                title: '商品管理',
                key: '/product',
                icon: <ToolOutlined />
            },
        ]
    },
    {
        title: '用户管理',
        key: '/user',
        icon: <UserOutlined />
    },
    {
        title: '角色管理',
        key: '/role',
        icon: <SafetyOutlined />,
    },
    {
        title: '图形图表',
        key: '/charts',
        icon: <AreaChartOutlined />,
        children: [
            {
                title: '柱形图',
                key: '/charts/bar',
                icon: <BarChartOutlined />
            },
            {
                title: '折线图',
                key: '/charts/line',
                icon: <LineChartOutlined />
            },
            {
                title: '饼图',
                key: '/charts/pie',
                icon: <PieChartOutlined />
            },
        ]
    },
]

通过map进行递归操作

getTreeNodes = (menuList) => {
        return menuList.map(item => {
            if (!item.children) {
                return {title: item.title, key: item.key}
            } else {
                return {title: item.title, key: item.key, children: this.getTreeNodes(item.children)}
            }
        })
    }