我的主要App.js组件使用D3绘制了一个散点图,而D3又绘制了一个散点图
单击分散点上的一个点时,将基于该点的值生成2个条形图之一(第一次单击时),或使用新数据进行更新(随后的单击时)。
使用下面的简化代码,而不是更新原始图表上的数据,而是通过每次单击将新的条形图附加到div元素上。如何更改barplot.js部分中的componentDidUpdate()代码,以便更新原始的barplot图表?
//Data is input here
const scatterPlotData = [
[5, 20], [48, 90], [250, 50], [100, 33], [330, 95],
[410, 12], [475, 44], [25, 67], [85, 21], [220, 88]
];
const bardata1 = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
const bardata2 = [ 1, 20, 33, 5, 7, 25, 22, 10, 1, 23,31, 2, 5, 40, 28, 27, 6, 8, 3, 5 ];
class ScatterPlot extends Component {
createScatterPlot() {
//d3 code here, relevant part which determines which barplot data to select
.on("click", function(d) {
//If x value of scatterplot point is >= 200, choose bar plot data above
if (d[0] >= 200) {
component.setState({ bardata: bardata2, event: d3.event });
} else {
component.setState({ bardata: bardata1, event: d3.event });
}
})
}
render() {
return (
<div>
{
//BarPlot class is called
this.state.bardata && this.state.event &&
<BarPlot bardata={this.state.bardata}/>
}
</div>
)
}
}
class BarPlot extends Component {
constructor(props){
super(props)
this.createBarPlot = this.createBarPlot.bind(this)
}
componentDidMount() {
this.createBarPlot()
}
componentDidUpdate(prevProps) {
if(JSON.stringify(this.props.bardata) !== JSON.stringify(prevProps.bardata)) {
this.setState({bardata: null});
this.createBarPlot()
}
}
createBarPlot() {
//d3 code here
}
render() {
return (
<div>
</div>
)
}
}
//Main app which calls the ScatterPlot class
class App extends Component {
constructor(props) {
super(props)
this.state = {
pointdata: pointdata1
}
}
render() {
return (
<div className="wrapper">
<header className="App-header">
Scatter Plot via React
</header>
<div id = 'plot-1'>
<ScatterPlot pointdata={this.state.pointdata} />
</div>
<div id="barplot"></div>
</div>
);
}