React丨antd tree 异步加载,只有首次点击加载,再次点击不加载

一、环境版本

  • antd 3.x tree

二、树形结构

  • 02
    • 0201
      • 020105
        • ZB0201000024
  • 07
    • 0701
      • 070101
        • ZB0701010001

三、问题描述

  • 异步加载,首次点击加载,再次点击不加载

四、解决方案

  • onExpand:展开/收起节点时触发

  • onLoad:节点加载完毕时触发

  • loadedKeys:(受控)已经加载的节点,需要配合 loadData 使用

  • expandedKeys:(受控)展开指定的树节点

五、代码

state = {
    treeExpandedKeys: [], 	// tree 展开节点 ['string,'string']
    treeLoadedKeys: [], 	// tree 已经加载节点
}
<Tree
    className={styles.eleTree}
    checkStrictly={true}
    expandedKeys={treeExpandedKeys}
    showIcon
    blockNode
    onExpand={this.handleTreeExpand}
    onSelect={this.handleTreeSelect}
    loadData={this.onLoadData}
    onLoad={this.onLoadTree}
    loadedKeys={this.props.treeLoadedKeys}
    >
    {this.renderTreeNodes(treeData)}
</Tree>
handleTreeExpand = (keys) => {
    const { dispatch, treeExpandedKeys, treeLoadedKeys } = this.props
    let newLoadKeys = treeLoadedKeys
    // 判断当前是展开还是收起节点,当前展开的长度比之前的少,说明是收起
    if (treeExpandedKeys.length > keys.length) {
      // 当是收起的时候,把这个收起的节点从loadedKeys中移除
      // newLoadKeys = treeLoadedKeys.filter((i) => keys.includes(i))
      let newStr = ''
      treeLoadedKeys.map(item => {
        if (!keys.includes(item)) {
          newStr = item
        }
      })
      let newArr3 = []
      treeLoadedKeys.map(item => {
        if (this.treeExpandcheckStr(item, newStr)) {
          if (item.length < newStr.length) {
            newArr3.push(item)
          }
        } else {
          newArr3.push(item)
        }
      })
      newLoadKeys = newArr3
      keys = newArr3
    }
    dispatch({
      type: 'draw3/save',
      payload: {
        treeLoadedKeys: newLoadKeys,
        treeExpandedKeys: keys
      }
    })
}
onLoadTree = loadedKeys => {
    const { dispatch } = this.props
    dispatch({
      type: 'draw3/save',
      payload: {
        treeLoadedKeys: loadedKeys
      }
    })
}
posted @ 2021-09-15 11:33  aivsok9  阅读(3334)  评论(0编辑  收藏  举报