我有一个React
组件正在使用Recharts中的BarChart
组件。但是,与其更新我的数据,不如为每条新数据添加条形图。另外,我已经为BarChart
实现了domains
,但是对于BarChart
也需要单独的hosts
。为此,我添加了一个名为formatDataForHostBarChart
的附加方法。
这是我的组成部分。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts';
class SuspiciousActivity extends Component{
constructor(props){
super(props);
this.state = {
suspiciousActivity: [
{
domains: [],
hosts: [],
}
]
}
this.formatDataForBarChart = this.formatDataForBarChart.bind(this)
}
formatDataForBarChart(data){
let chartArray = [];
if (data && data.length > 0) {
data.map(activity => {
activity.domains.map((domain) => {
const chartData = {
name: domain.domainName,
riskScore: domain.riskScore
}
chartArray.push(chartData)
})
})
}
return chartArray;
}
formatDataForHostBarChart(data){
let chartArray = [];
if (data && data.length > 0) {
data.map(hostActivity => {
hostActivity.hosts.map((host) => {
const chartData = {
name: host.ipAddress,
primaryKey: host.primaryKey,
riskScore: host.riskScore
}
chartArray.push(chartData)
})
})
}
return chartArray;
}
render(){
return (
<div>
<div className="row">
<div className="col-md-6">
<div className="row">
<div className="col-md-12"><label style={TitleColor}>Top 10 Suspicious Domains</label></div>
</div>
<div className="row">
<div className="col-md-12">
<BarChart
width={400}
height={300}
data={this.state.suspiciousActivity}
margin={
{
top: 5, right: 30, left: 20, bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="riskScore" fill="#8884d8" />
</BarChart>
</div>
</div>
</div>
<div className="col-md-6">
<div className="row">
<div className="col-md-12">
<label style={TitleColor}>
Top 10 Suspicious Hosts
</label>
</div>
</div>
<div className="row">
<div className="col-md-12">
<BarChart
width={400}
height={300}
data={this.state.suspiciousActivity.hosts}
margin={
{
top: 5, right: 30, left: 20, bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="pv" fill="#8884d8" />
</BarChart>
</div>
</div>
</div>
</div>
</div>
);
}
};
SuspiciousActivity.propTypes = {
suspiciousActivity: PropTypes.arrayOf(PropTypes.objectOf(PropTypes.any)).isRequired,
// suspiciousActivityStructure: PropTypes.arrayOf(PropTypes.objectOf(PropTypes.any)).isRequired,
};
export default SuspiciousActivity;
我应该如何重构此代码以更新数据,而不是添加新数据,并重用该功能在新的BarChart
上显示不同的数据。