react 实现递归 不知道为啥渲染不到 初学者在线求教 急急急!!!感恩大佬

图片说明

import React, {Component} from "react";
import {connect} from "react-redux";
import { Tree, Icon } from 'antd';


const {TreeNode} = Tree ;


class BasicArea extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeArr: []
    }
  }



  data= [
    {
      "id":1,
      "name":"一级节点",
      "parentId":0,
      "isValid":true,
      "canAddChild":true,
      "parent":null,
      "children":[]
    },{
      "id":3,
      "name":"二级节点",
      "parentId":1,
      "isValid":true,
      "canAddChild":true,
      "parent":null,
      "children":[]
    },{
      "id":3,
      "name":"二级节点",
      "parentId":0,
      "isValid":true,
      "canAddChild":true,
      "parent":null,
      "children":[]
    },{
      "id":3,
      "name":"二级节点",
      "parentId":0,
      "isValid":true,
      "canAddChild":true,
      "parent":null,
      "children":[]
    },{
      "id":3,
      "name":"二级节点",
      "parentId":0,
      "isValid":true,
      "canAddChild":true,
      "parent":null,
      "children":[]
    }

  ]

  createTree = data => {
    let treeArr = [];
    //获取顶级父元素集合
    let roots = data.filter( elemt => elemt.parentId === 0 );
    treeArr.push(...roots);
    //从顶级元素开始,获取每个元素的子元素放到该元素的children树形中
    const getChildren = (resultarr, data) => {
      resultarr.forEach ((elemt,index) => {
        elemt.children = data.filter((item,index) => item.patentId === elemt.id );
        //判断当前元素是不是有子元素被添加, 如果有, 再在子元素这一层循环
        if( elemt.children.length > 0){
          getChildren(elemt.children,data);
        }
      });
    }
    getChildren(treeArr,data);
    console.log(treeArr);
    //最后更新一下数据
    this.setState({
      treeArr
    })

  };

  renderTree = treeArr => treeArr.map ( value => {

    //理论上支持无限深度的树状目录
    //遍历树状数组,如果发现他有children则先套上<TreeNode></TreeNode>,在对他children中的元素做相同的操作,直到children为空的元素停止
    //说明他已经是最深的那一层了
    if(value.children) {
      return(
        <TreeNode title ={
          <span>
            {value.name}
            <Icon type="plus" />
          </span>
        } key={value.id}>
          {/* 对children中的每个元素进行递归 */}
          {this.renderTree(value.children)}
        </TreeNode>
      )
    }

  });




  render(){
    return(
      <Tree>

        {this.renderTree(this.state.treeArr)}
      </Tree>
    )
  }

  componentDidMount(){
    this.createTree();
  }

}

export default connect(null, null)(BasicArea);

2个回答

你方法执行顺序有问题!createTree 执行时没有传参数,参数上的data类型还是字符串!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问