React 怎样实现循环出整个类目?

新手上路,请多包涵

现在有一个类目信息需要循环出来。
需要从根类目开始遍历获取整个类目树。即:先传0获取所有一级类目ID,然后在通过获取到的一级类目ID遍历获取所二级类目,最后通过遍历二级类目ID获取三级类目,下面是我写的,获取到一级目录就不知道怎么写了,不知道是不是写法不对

//查询商品分类
querycategory=()=>{

  window.bridge.call('open.api.request', {
      version: '1',
      namespace: 'com.alibaba.product',
      name: 'alibaba.category.get',
      data: {

        categoryID:this.state.categoryID, // 初始化查询根目录 categoryID=0
        webSite:"1688"
      }
  }, (res) => {

  {/* 得到商品分类信息*/}
  const categoryList=res.result.data.categoryInfo[0].childCategorys;
    this.setState({
categoryData:categoryList
} )

  });


}


//加载商品分类
categorylist=()=>{
  const list=this.state.categoryData;
  const lists=list.length
  ?
  list.map((newlist,index)=>(
    //一级类目
    <TreeNode label={newlist.name} key={newlist.id}>
           {/* 二级目录要通过一级目录的iD调用接口查寻出来,要怎么操作,直接调用querycategory()? */}
            <TreeNode label="二级目录" key="0">
            </TreeNode>

     </TreeNode>

  ))
:''
;
return lists;
}

图片描述

刚学React 不知道怎么弄,求教!

阅读 1.9k
1 个回答
import React, {Component} from 'react';

import PropTypes from 'prop-types';

class Tree extends Component {

  static propsTypes = {
    dataSource: PropTypes.shape({
      name: PropTypes.string,
      id: PropTypes.string,
    }),
  };

  get getChildren() {
    return this.props.dataSource.map(item => {
      <TreeNode key={`tree-${item.id}`} label={item.name} id={item.id}/>;
    });
  }

  render() {
    return (
        <div className={'tree'}>
          {this.getChildren}
        </div>
    );
  }
}

class TreeNode extends Component {
  static propsTypes = {
    label: PropTypes.string,
    id: PropTypes.string,
  };

  state = {
    loadData: false,
    close: true,
  };

  data = {
    list: [],
  };

  async loadData() {

    this.data.list = [];

  }

  async open() {
    let {loadData, close} = this.state;

    if (!loadData) {
      await this.loadData();
      loadData = true;
    }

    this.setState({
      loadData,
      close: !close,
    });
  }

  get getChildren() {
    return this.data.list.map(item => {
      <TreeNode key={`tree-${item.id}`} label={item.name} id={item.id}/>;
    });
  }

  render() {
    const {label} = this.props;
    const {list} = this.data;
    return (
        <div onClick={this.open.bind(this)} className={'tree-node'}>
          {label}
          {list.length > 0 ? this.getChildren : ''}
        </div>
    );
  }
}

大概就是这个样子了,后续你还要增加样式,还有判断是否有下级类目,有的话允许展开,没有就是最后一级

推荐问题