D3 折线图组件未在 React 的 useEffect 中更新

D3 line chart component not being updated inside useEffect in React

我正在从 API 接收折线图数据。每次更新数据时,它不会重新绘制平滑过渡,而是在现有图表的顶部绘制新线。看起来很乱。我在唱歌时没有生命周期 useEffect。跟line().remove().merge()有关系吗?我做错了什么?

CodeSandbbox

useEffect(() => {
    const svg = d3
      .select(svgRef.current)
      .append("g")
      .attr("transform", "translate(0," + -130 + ")");
    const xScale = d3.scaleTime();
    const yScale = d3.scaleLinear();
    const xAxisDateFormat = d3.timeFormat("%b");
    
    // line generator
    const line = d3
      .line()
      .curve(d3.curveCatmullRom.alpha(1))
      .x((d) => xScale(new Date(d.date)))
      .y((d) => yScale(d.value));

    // draw line chart
    const lines = svg.append("g").attr("class", "lines");
    lines
      .selectAll(".line-group")
      .data(lineChartData.values)
      .enter()
      .append("g")
      .attr("class", "line-group")
      .append("path")
      .attr("class", "line")
      .attr("stroke", (d, i) => colorScale(d.lineColor))
      .attr("d", (d) => line(d.dataset));
  }, [lineChartData]);

exit() 在您的代码中缺失:

const lines = svg.append("g")
  .classed("lines", true);
const groups = lines
  .selectAll(".line-group")
  .data(lineChartData.values);

const newGroups = groups.enter()
  .append("g")
  .classed("line-group", true);

newGroups.append("path")
  .classed("line", true)
  .attr("stroke", (d, i) => colorScale(d.lineColor))
  .attr("d", (d) => line(d.dataset));

const oldGroups = groups.exit();
oldGroups.remove();

您可以在添加新元素之前清除您的 svg 内容。

而不是:

const svg = d3
      .select(svgRef.current)
      .append("g")

做:

 const svgEl = d3.select(svgRef.current);

 svgEl.selectAll('*').remove();

 const svg = svgEl
      .append('g')