首页 > 解决方案 > 为什么数据更新后我的输入选择不为空?

问题描述

我使用 d3 作为反应项目的一部分。在某些时候,我会显示数据(javascript 对象数组),如下所示。

当我更新二维数据数组时,我想更新更新对象的位置+大小并有条件地绘制边框。

但是,我注意到,d3 不仅更新与更新数据相关的 svg 对象,还总是更新我的数据数组的第一个元素并对所有其他元素执行输入操作。尽管对象没有改变。数组引用也应该相同。

这是为什么?

let bound = d3
  .select(this.svgRef.current)
  .selectAll(".square")
  .data(this.props.data, d => d);

//enter
bound
  .enter()
  .append("rect")
  .attr("class", "square")
  .attr("id", d => d.id)
  .attr("x", d => {console.log("enter", d); return d.x})
  .attr("y", d => d.y)
  .attr("width", d => d.width)
  .attr("height", d => d.height)
  .style("fill", d => {
    return d.c;
  })
  .style("stroke", d => {
    if (d.id == this.props.focus) {
      return "#FF0000";
    } else {
      return null;
    }
  });

//updates
bound
  .attr("x", d => { return d.x })
  .attr("y", d => d.y)
  .attr("width", d => d.width)
  .attr("height", d => d.height)
  .style("fill", d => {
    return d.c;
  })
  .style("stroke", d => {
    if (d.id == this.props.focus) {
      return "#FF0000";
    } else {
      return null;
    }
  });


bound.exit().remove();

数据格式如下:

[{
  "id":"1.png","c":"#FFFFFF",
  "d":["No Data"],
  "index":0,
  "x":0,
  "y":0,
  "width":115,
  "height":16
}, { 
  "id":"2.png",
  "c":"#FFFFFF",
  "d":["Example Data"],
  "index":1,
  "x":115,
  "y":0,
  "width":115,
  "height":16
}, ...]

标签: d3.js

解决方案


我的问题的答案似乎是一个不正确的键功能。标识函数似乎不适用于对象数组。


推荐阅读