在这个例子中,我'm trying to update data bound to selection, I' m在变量中存储选择并更新数据https://codepen.io/anon/pen/ebYKRK

let data = ['red'];

d3.select('svg').append('g');
let selection = d3.select('svg').select('g').selectAll('circle');
selection
  .data(data, d => d)
  .enter().append('circle')
    .attr('r', 4)
    .attr('fill', d => d)
    .attr('cx', (d, i) => 10 + 10 * i)
    .attr('cy', (d, i) => 10 + 10 * i)
    ;

setTimeout(() => {
  data = ['red', 'green'];
  // this will work -> d3.select('svg').select('g').selectAll('circle')
  selection
    .data(data, d => d)
      .attr('fill', 'black')
    .enter().append('circle')
      .attr('r', 4)
      .attr('fill', d => d)
      .attr('cx', (d, i) => 30 + 10 * i)
      .attr('cy', (d, i) => 30 + 10 * i)
      ;
}, 2000)

我希望这段代码可以使现有的 red 圈成为 black ,但它不会像这样工作,而是像创建新圈子一样 . 但是,如果我使用完整的d3选择器,它会按预期工作(现有的圆圈变为黑色) .

我试图理解为什么如果我将选择器存储在变量中,这不起作用?或者,如果这种方式不正确的代码,那么每次避免编写完整的d3选择器的正确方法是什么?