首页 > 解决方案 > D3 组件不会在 React 中更新

问题描述

单击按钮时,我正在尝试更新一些条形图。

这是按钮

  <button className="login_buttons" onClick={this.setRecommendations}>
            Click to See Top Tracks and Recommendations
          </button>

它调用这个函数,它确实成功地更新了所有状态,现在图表显示虚拟数据就好了。

setRecommendations(){
    getAlbums().then(albums =>{
      this.setState({topAlbums: albums[0]});
      this.setState({album_count: albums[1]});
    });
    getArtists().then(artists =>{
      this.setState({topArtist: artists[0]});
      this.setState({artist_count: artists[1]});
    });
    getGenres().then(genres =>{
      this.setState({topGenre: genres[0]});
      this.setState({genre_count: genres[1]});
    });
    popularityData().then(popData =>{
      this.setState({popRange: popData[0]});
      this.setState({pop_count: popData[1]});
    });
    recommendations().then(recs => {
      this.setState({recommendations: recs});
    });
  }

这是我的图表组件

import React from 'react';
import * as d3 from "d3";

class Graphs extends React.Component {
  componentDidMount() {
    this.drawChart();
  }

  componentDidUpdate() {
       d3.select(`#${this.props.graphID}`).remove()
       this.drawChart();
      }

  drawChart() {
    const data = this.props.data;
    const labels = this.props.axisLabels;
    const title = this.props.title;
    const margins = {top:50, right:50, bottom:50, left:50}
    const h = 600 - margins.top - margins.bottom;
    const w = 600 - margins.right - margins.left;
    var x = d3.scaleBand()
              .range([0, w])
              .domain(labels);
    var y = d3.scaleLinear()
              .range([h, 0])
              .domain([0, d3.max(data)]);

    const svg = d3.select(`#${this.props.graphID}`)
                  .append("svg")
                  .attr("width", w + margins.right + margins.left)
                  .attr("height", h + margins.top + margins.bottom)
                  .append("g")
                  .attr("transform", `translate(${margins.left}, ${margins.top})`);

          svg.selectAll("rect")
            .data(data)
            .enter()
            .append("rect")
            .attr("y", (d) => y(d))
            .attr("x", (d, i) => (x.bandwidth()*i + 10))
            .attr("height", (d) => h - y(d))
            .attr("width", x.bandwidth() - 10)
            .attr("fill", "blue");

          svg.append("g")
              .attr("transform", `translate(0, ${h})`)
              .call(d3.axisBottom(x))

          svg.append("g")
              .call(d3.axisLeft(y));

          svg.append("text")
              .attr("x", (w/2))
              .attr("y", 0 - (margins.top / 2))
              .attr("text-anchor", "middle")
              .style("font-size", "16px")
              .style("fill", "white")
              .style("text-decoration", "underline")
              .text(title);
  }

    render(){
      return <div id={this.props.graphID} />
    }
}
export default Graphs

当我单击按钮时,其中包含虚拟数据的图表现在确实消失了,因此componentsWillUpdate被称为但它没有重绘图表,我不明白为什么,因为compnentsDoMount调用this.drawChart()好了。

标签: javascriptreactjsd3.js

解决方案


不要移除容器:

 d3.select(`#${this.props.graphID}`).remove()

删除其中的内容:

d3.select(`#${this.props.graphID}`).selectAll('*').remove()

推荐阅读