鍍金池/ 問答/Android  HTML/ React 怎樣實(shí)現(xiàn)循環(huán)出整個(gè)類目?

React 怎樣實(shí)現(xiàn)循環(huán)出整個(gè)類目?

現(xiàn)在有一個(gè)類目信息需要循環(huán)出來。
需要從根類目開始遍歷獲取整個(gè)類目樹。即:先傳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調(diào)用接口查尋出來,要怎么操作,直接調(diào)用querycategory()? */}
            <TreeNode label="二級目錄" key="0">
            </TreeNode>

     </TreeNode>

  ))
:''
;
return lists;
}

圖片描述

剛學(xué)React 不知道怎么弄,求教!

回答
編輯回答
胭脂淚
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>
    );
  }
}

大概就是這個(gè)樣子了,后續(xù)你還要增加樣式,還有判斷是否有下級類目,有的話允許展開,沒有就是最后一級

2018年6月4日 12:26