鍍金池/ 問答/HTML/ ant-design Tree組件問題

ant-design Tree組件問題

一個異步加載的tree組件初始狀態(tài)是這樣:

clipboard.png

此時的treeData是:

    treeData: [
      {
        title: 'Expand to load', key: '0', children: [
          { title: 'child', key: '0-0', isLeaf: false }
        ]
      }
    ]

點(diǎn)擊+號,模擬異步請求數(shù)據(jù),擴(kuò)展成這樣:

clipboard.png

此時的狀態(tài)是:

    treeData: [
      {
        title: 'Expand to load', key: '0', children: [
          { title: 'child', key: '0-0', isLeaf: false ,children:[
              { title: 'Child Node', key: "0-0-0" },
              { title: 'Child Node', key: "0-0-1" }
          ]}
        ]
      }
    ]

然后,此時點(diǎn)擊按鈕,希望返回初始狀態(tài):

    treeData: [
      {
        title: 'Expand to load', key: '0', children: [
          { title: 'child', key: '0-0', isLeaf: false }
        ]
      }
    ]

但是實(shí)際結(jié)果是:

clipboard.png

問題是:

  1. child前面并不是+號(不能點(diǎn)擊),但是狀態(tài)isLeaf設(shè)置的是false
  2. Expand to load展開了,希望的是不展開

感覺是Tree組件并沒有重新渲染,而是在原來的基礎(chǔ)上update state。求助怎么解決?

主要代碼:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Tree } from 'antd';

const TreeNode = Tree.TreeNode;

class Demo extends React.Component {
  state = {
    treeData: [
      {
        title: 'Expand to load', key: '0', children: [
          { title: 'child', key: '0-0', isLeaf: false }
        ]
      }
    ],
  }

  onLoadData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      setTimeout(() => {
        console.log(treeNode);
        treeNode.props.dataRef.children = [
          { title: 'Child Node', key: `${treeNode.props.eventKey}-0` },
          { title: 'Child Node', key: `${treeNode.props.eventKey}-1` },
        ];
        this.setState({
          treeData: [...this.state.treeData],
        });
        resolve();
      }, 1000);
    });
  }

  btnClick = () => {
    this.setState({
      treeData: [
        {
          title: 'Expand to load', key: '0', children: [
            { title: 'child', key: '0-0', isLeaf: false }
          ]
        }
      ],
    });
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item} />;
    });
  }

  render() {
    return (
      <div>
        <Tree loadData={this.onLoadData} showLine>
          {this.renderTreeNodes(this.state.treeData)}
        </Tree>
        <button onClick={this.btnClick}>更新treedata</button>
      </div>
    );
  }
}

ReactDOM.render(<Demo />, document.getElementById('root'));

如果需要的話,可以到這邊直接下載demo:https://github.com/wyzgo/antd_test.git

回答
編輯回答
真難過

應(yīng)該是要手動設(shè)置tree的expandKeys

2018年2月8日 17:23