[英]d3 v4 + react + es6 + crossfilter: Selection.exit().remove() not working
我正在使用帶有ES6風格React的crossfilter.js和d3.js v4 ,以嘗試使用上下文畫筆制作尺寸圖。 本質上,我以這個示例為例 ,並將其轉換為ES6。
我遇到的問題是selection.exit().remove()
無法正常工作,因此在每次重繪時,越來越多的圓圈會附加到svg g元素上。 創建筆刷時會觸發重畫。 我通過跑步檢查
selection.exit()
.attr('class', d => {
console.log('anything');
return 'anything';
})
.remove();
但沒有輸出任何內容,因此我認為我的數據選擇無效。
這里是上下文:
componentDidMount() {
const el = ReactDOM.findDOMNode(this); // the mounted svg element
const svg = d3.select(el)
.attr('width', 300)
.attr('height', 500);
const g = svg.append('g')
.attr('transform', 'translate(32,32)');
let circles = g.append('g')
.selectAll('circle');
const brushGroup = g.append('g')
.attr('class', 'brush')
.call(brush);
function redraw() {
const all = group.all(); // crossfilter group returns an array
xAxisGroup.call(xAxis);
yAxisGroup.call(yAxis);
circles = circles.data(all, d => d); // keyFn for data constancy
circles.enter().append('circle')
.attr('r', radius)
.attr('cx', plotX) // radius + plotX/Y are simple curry functions
.attr('cy', plotY);
circles.exit().remove(); // not working!!
}
redraw();
}
我也知道v4中d3-selection的這一變化,但是我不太確定哪些行是我的update
,哪些行是我的update + enter
。
任何幫助將非常感激。 謝謝!
我懷疑問題是2件事之一。 可能是下面的#1。 很難給出一個可行的示例來進行測試,但是在這里您可以執行以下操作:
我相信selectAll
和data
聯接應該在redraw
函數中一起發生。 因為您從未在重繪函數中重做selectAll
,所以您的選擇將永遠不會包含任何元素。 如果您在redraw
功能中檢查了enter
和exit
選擇,則enter
選擇將始終包含所有數據點,因為基礎選擇為空。
您的數據鍵函數返回一個對象。 由於該對象是group.all
的group.all
的結果,因此它們應通過引用進行比較,但是使用circles.data(all, d => d.key)
會更安全。
解決方案應該是執行以下操作:
componentDidMount() {
const el = ReactDOM.findDOMNode(this); // the mounted svg element
const svg = d3.select(el)
.attr('width', 300)
.attr('height', 500);
const g = svg.append('g')
.attr('transform', 'translate(32,32)');
let circlesGroup = g.append('g'); // Just hang on to the group
const brushGroup = g.append('g')
.attr('class', 'brush')
.call(brush);
function redraw() {
const all = group.all(); // crossfilter group returns an array
xAxisGroup.call(xAxis);
yAxisGroup.call(yAxis);
let circles = circlesGroup // Do the selection and data join here
.selectAll('circle')
.data(all, d => d.key); // Have the key function return a key, not an object
circles.enter().append('circle')
.attr('r', radius)
.attr('cx', plotX) // radius + plotX/Y are simple curry functions
.attr('cy', plotY);
circles.exit().remove();
}
redraw();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.