reactjs - 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)
我已经尝试了一切都没有成功。请给我一些帮助。
解决方案
推荐阅读
- apache-spark-sql - apache spark sql表覆盖问题
- python-3.x - 描述跨 AWS 区域的 RDS 快照
- r - 如何在 r 中拉伸直方图中的 y 轴,以使低值变得更加明显?
- python - 使用 odeint 输出值
- python - 从 Wagtail 2.7.1 迁移到 2.7.4 的问题
- reactjs - 在 reactjs 中,是否可以创建一个不重置内容状态的选项卡控件?
- angular - 使用 mat-* 元素时如何使用可扩展行示例修复此材料表
- python - 使用 Python 和 dotenv 更改保存在 .env 文件中的环境变量
- python-3.x - 获取一组列的当前值和下一个值(在每个组中)
- c# - 找不到 .NET Core 项目