更新 D3 上的力图。图重复而不是更新

Updating force-graph on D3. Graph duplicates instead of updating

谁能帮我解决一下更新模式?现在这就是我给我的图表 React 组件新数据时得到的……旧数据保持不变…… 这是我的代码 https://github.com/danieltkach/react-d3-integration 我一直在阅读它,我知道我必须在这里做“东西”......用 join() 替换 enter ?然后里面的3个update函数呢? ...

// SVGs creation ---
        const linkSvg = svgRef.current
            .selectAll('path')
            .data(LINKS, d=>d.agentName)
            // .enter()
            .join(
                enter => enter.append('path')
                    .attr('stroke', d => !d.weight ? "gray" : linkStyles.onlineColor)
                    .attr('stroke-width', d => linkWeightScale(d.weight))
                    .attr('stroke-dasharray', d => {
                        if (!d.weight) return linkDashedScale(d.weight)
                    }),
                update => update,
                exit => exit.call(exit=>exit).remove()
            )

我认为你的问题出在 GraphGenerator.jsx:

    svgRef.current = d3.select('#viz')
        .attr('width', svgWidth)
        .attr('height', svgHeight)
        .append('g') // a new group is appended 

您每次都在附加一个新的 g 元素。该新元素没有数据,因此在连接中没有删除或更新任何内容。如果您删除 .append('g') 它应该可以工作。

编辑:

在您的节点创建中进一步向下使用:

    const circles = svgRef.current
        .selectAll()
        .data(NODES)
        .join("g");

您没有选择任何内容,因此无法更新任何内容。在那里使用它:

const circles = svgRef.current
            .selectAll('.node')
            .data(NODES)
            .join("g")
            .classed('node',true)