D3.js keep running into this error TypeError: Cannot read properties of null (reading 'ownerDocument')?

D3.js keep running into this error TypeError: Cannot read properties of null (reading 'ownerDocument')?

当我尝试为我的 d3 图创建图例时,我一直 运行 进入此错误

TypeError: 无法读取 null 的属性(读取 'ownerDocument') 在新的 EnterNode (enter.js:9)

8 export function EnterNode(parent, datum) {

9 this.ownerDocument = parent.ownerDocument;

这只会偶尔发生,并非总是如此, 我的 d3 配置;

 private data: SimpleDataModel[] = [
    { name: `Value 1`, value: '25', color: '#254C66' },
    { name: `Value 2`, value: '75', color: '#49A0CC' },
  ];
this.createSvg();
this.createLegend();
private createSvg(): void {
    this.d3
      .select(this.figureElement.nativeElement)
      .append('svg')
      .attr('viewBox', `0 0 ${this.width} ${this.height}`);

    this.svg = this.d3
    .select(this.figureElement.nativeElement)
    .select('svg');

    this.legend = this.svg
      .append('g')
      .attr('id','legend');

    this.graphGroup = this.svg
      .append('g')
      .attr(
        'transform',
        'translate(' + this.width / 2 + ',' + this.height / 2 + ')'
      );
  }

  private createLegend(): void {

     const legend1 = this.svg.select('g#legend')
      .data(this.data)   =====>ERROR OCCURS AT THIS LINE
      .enter();

    legend1.append('rect')
      .attr('fill', d => this.colors(d.name))
      .attr('height', 15)
      .attr('width', 15);

    legend1.append('text')
      .attr('x', 18)
      .attr('y', 10)
      .attr('dy', '.15em')
      .text((d, i) => d.name)
      .style('text-anchor', 'start')
      .style('font-size', 24);
    }

有时,如果我以不同方式配置我的数据输入,它会起作用,但有时它会不起作用。我做错了什么?

我想通了,错误是因为正在渲染另一个 g 元素,但上面没有 id 图例。使用

修复了它
const legend1 = this.svg.selectAll('g')
      .select('#legend')
      .data(this.data)
      .enter();