首页 > 解决方案 > D3-层次结构:使用不同数据重新渲染后节点未定义

问题描述

我目前正在用 D3 构建一个层次结构条形图,除了我尝试用新数据重新渲染新图表时,一切工作正常。

这是父组件:

const MetricsSubmetricsOverall = ({ scores }) => {
  const d3Chart = useRef();

  useEffect(() => {
    createChart(d3Chart.current, scores);
    return () => {};
  }, [scores]);

  return (
    <div>
      <svg ref={d3Chart} />
    </div>
  );
};

export default MetricsSubmetricsOverall;

其中 score 是我获取到后端的数据,它会随着某些过滤器的变化而变化。

这是 createChart 函数:

createChart(d3Chart, scores) {
  const svg = d3.select(d3Chart).attr("width", width).attr("height", height);

  let root = d3
    .hierarchy(scores)
    .eachBefore((d) => console.log(d))
    .sum((d) => (d.value ? d.value : d.sum / d.responses - d.valueSum))
    .sort((a, b) => b.value - a.value)
    .eachAfter(
      (d) =>
        (d.index = d.parent ? (d.parent.index = d.parent.index + 1 || 0) : 0)
    );

  svg
    .append("rect")
    .attr("class", "background")
    .attr("fill", "none")
    .attr("pointer-events", "all")
    .attr("width", width)
    .attr("height", height)
    .attr("cursor", "pointer")
    .on("click", (event, d) => up(svg, d));

  svg.append("g").call(xAxis);

  svg.append("g").call(yAxis);

  down(svg, root);
  svg.node();
}

其中 up 和 down 是控制点击时向上或向下层次结构的两个函数。因此,每当我使用新的分数数据重新渲染我的组件并单击以向下或向上移动层次结构时,我都会收到以下错误消息:

'TypeError: Cannot read property 'parent' of undefined'.
 export function up(svg, d) {
  if (!d.parent || !svg.selectAll(".exit").empty()) return;

  // Rebind the current node to the background.
  svg.select(".background").datum(d.parent)

我已经尝试了一切都没有成功。请给我一些帮助。

标签: reactjsd3.jsreact-hooks

解决方案


推荐阅读