我在使用 D3.js 处理嵌套数据时遇到问题
数据由代表类别
的对象数组组成。
每个类别都有多个 checkin
。
我想要每个 category
都有一个部分,并在其中为每个 checkin
一个 div。我随着时间的推移操纵数据,并依靠 D3.js 的更新、进入和退出机制将数据正确输出到 DOM。
我不明白的是:
- 为什么当调用第二次更新时,旧数据不会出现在 exit() 集中,因此不会被删除?
- 为什么当再次使用
data1
第三次调用update()
时,尽管提供了数据中的关键功能,但条目仍会再次追加 ?根据我目前的理解,D3 应该认识到这实际上是一个更新,并且具有相同 key 的数据已经存在于该部分中。
第二个问题可能与第一个问题有关,但现在我不确定。
这是一个交互式 bl.ocks.org:https://bl.ocks.org/mattleonowicz/fd975a6d914f90c9934464df57e498c9
下面相同的代码:
<html>
<body>
<div id="app" />
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
const data1 = [
{
category: {
id: 1
},
checkins: [
{
lat: 1,
lon: 1
},
{
lat: 2,
lon: 2
}
// ... more objects like this would normally be here
]
}
// ... more objects like this would normally be here
];
const data2 = [
{
category: {
id: 1
},
checkins: [
{
lat: 3,
lon: 3
},
{
lat: 4,
lon: 4
}
// ... more objects like this would normally be here
]
}
// ... more objects like this would normally be here
];
update(data1);
setTimeout(() => update(data2), 2000);
setTimeout(() => update(data1), 4000);
function update(data) {
const categoriesData = d3.select('#app')
.selectAll('section')
.data(data, d => d.category.id);
// CATEGORIES EXIT
categoriesData.exit()
.remove();
// CATEGORIES UPDATE + ENTER - bind all categories with their checkins
const checkinsData = categoriesData.enter()
.append('section')
.merge(categoriesData)
.selectAll('section')
.data(d => d.checkins, d => `${d.lon},${d.lat}`);
// CHECKINS UPDATE : nothing, because checkins will only come and go
// CHECKINS EXIT
checkinsData.exit()
.remove();
// CHECKINS ENTER
checkinsData.enter()
.append('div')
.html(d => `${d.lon},${d.lat}`);
}
</script>
</body>
</html>
最佳答案
您这里有一个拼写错误:
// CATEGORIES UPDATE + ENTER - bind all categories with their checkins
const checkinsData = categoriesData.enter()
.append('section')
.merge(categoriesData)
-> .selectAll('section')
.data(d => d.checkins, d => `${d.lon},${d.lat}`);
您想在第二个选择中写入 .selectAll('div')
。
关于javascript - D3.js 和嵌套数据 - 为什么我的 exit() 设置为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502524/