javascript - 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()
好了。
解决方案
不要移除容器:
d3.select(`#${this.props.graphID}`).remove()
删除其中的内容:
d3.select(`#${this.props.graphID}`).selectAll('*').remove()
推荐阅读
- java - OkHttp3Connection 代码 403 错误
- regex - React - 使用 Regex 突出显示 dangerouslySetInnerHTML 中的文本。工作不可靠
- ionic-framework - 检查(单击)按钮上的值或
- android - 在 Fragment 中使用 CardView 的 GridLayout
- ilnumerics - 更新 ILNumerics ILSurface 的 z 值
- java - 将 OAuth2 登录映射到自定义主体
- css - 使用 css 对图标执行动画“脉冲”
- python-3.x - 循环变量流水线和单独使用的函数集
- html - 居中时如何“自动扩展”CSS网格单元以填充可用空间?
- aws-cli - 用于在 s3 存储桶中搜索文件的 AWS CLI