【问题标题】:how to update d3 graph in react using redux actions?如何使用 redux 操作更新 d3 图?
【发布时间】:2020-08-26 18:37:44
【问题描述】:

我正在尝试使用鼠标事件(mouseenter、mouseleave)中调用的 redux 操作来存储工具提示中的数据。

问题:当鼠标光标位于元素(g 元素)上时,我预计只有mouseenter 事件,但mouseleave 也会被触发。这会导致更新 redux 存储并在循环中重新渲染 react 组件。

我有一个 svg 元素,然后我附加了 g 元素,它是圆形和文本的包装器。我在 g 元素上添加了事件监听器。

这是我的代码:

const SomeReactComponent =() => {
const dispatch = useDispatch();

const createChart = () => {

    const svg = d3
      .select(svgNode)
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
      .style('border', '2px solid black')
      .append('g')
      .attr(
        'transform',
        `translate(${width / 2 + margin.left / 2},${height / 2 + margin.top})`
      );

const Tooltip = d3
        .select('.polar-scatter-chart')
        .append('div')
        .attr('class', 'tooltip');

const wrapper = svg
      .selectAll('Points')
      .data(newData)
      .enter()
      .append('g')
      .on('mouseenter', ({ id, name, themeName }) => {
        Tooltip.html(name)
          .style('visibility', 'visible')
          .style('top', `${d3.event.pageY - 350}px`)
          .style('left', `${d3.event.pageX}px`);
          dispatch(handleTooltip({ id, themeName }));
        }
      })
      .on('mouseleave', () => {
        Tooltip.style('visibility', 'hidden');
          dispatch(handleTooltip({ id: '', themeName: '' }));
      });
    wrapper
      .append('circle')
      .attr('class', 'point')
      .attr('transform', (d, i) => {})
      .attr('r',7)

    wrapper
      .append('text')
      .attr('transform', (d) => {})
      .text((d) => some_text);
  };
 }

 createChart();

  return (
    <div className="polar-scatter-chart">
      <svg ref={svgRef} />
    </div>
  );
}

如何使用 redux 操作正确更新 d3 图形?

感谢回答

【问题讨论】:

    标签: reactjs d3.js redux redux-toolkit


    【解决方案1】:

    您在每次渲染时调用 createChart,创建一组全新的元素,这些元素可能位于已经存在的元素之上。 因此,每次,您“离开”旧元素,因为您“进入”了绘制在顶部的元素。

    如果您想这样做,您应该将createChart 包装在useEffect 调用中,并且只执行一次。

    但更好的主意是使用 D3 库进行反应。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2021-09-18
      • 2014-03-29
      • 1970-01-01
      • 2022-08-17
      相关资源
      最近更新 更多