【问题标题】:d3js Collapsible tree dynamic data from API not working来自API的d3js可折叠树动态数据不起作用
【发布时间】:2021-12-16 01:27:57
【问题描述】:

我正在使用这个例子和 ReactJS 来绘制一个可折叠的树形图。 示例 - https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5ecd。我面临的问题是,我的孩子是在单击节点时从 API 端点获取的,而不是一次全部获取,因为这可能会降低页面的性能。我的状态中有示例中提到的 treeData,在从 API 获取数据后,我正在更新状态,但是如何更新正在单击的子节点并显示获取的数据。在示例中,由于所有数据都已经存在,因此以下方法可以正常工作。

    function click(d) {
// API call here and after fetching the data continue with the below code. The problem here is the state data is updated but I don't think the graph is updating along with that.
    if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
    update(d);
  }

有人可以帮我解决这个问题吗?提前致谢。

【问题讨论】:

    标签: javascript reactjs d3.js data-visualization


    【解决方案1】:

    这个不好说,因为我没有api可以测试,但是你需要把新旧数据结合起来,把数据转换成d3.hierarchy,在新节点上加上._children。无论如何,这应该是一个开始。

    function click(d) {
        // get your new data
        const new_data = await getData() // or whatever 
        
        // combine new data with old data, I'm assuming this will update treeData but I'm not sure
        d.children.push(new_data) 
    
        // call the hierarchy on new data so it has the mike magic it needs
        root = d3.hierarchy(treeData, di => di.children)
    
        // add the ._children attribute
        d.children.forEach(di => collapse)
    
        // continue as usual
        if (d.children) {
            d._children = d.children;
            d.children = null;
          } else {
            d.children = d._children;
            d._children = null;
          }
        update(d);
      }
    

    我尚未对此进行测试,但这是我要开始的地方。

    ** 编辑 ** d.children.push(new_data) 可能不起作用。您可能需要在原始treeData 中找到节点并将其添加到该节点的子节点中,因为d 已经通过层次结构进行了转换。但是如果您可以将其添加到d,这听起来更容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多