我正在尝试使用react和chartjs绘制饼图。
我正在调用这样的API: -
const border ={
border:'1px solid blue',
borderRadius: '25px',
padding:'15px',
marginTop:'20px'
}
class ScreenView extends Component {
constructor(){
super();
this.state = {
newUsers:'',
allUsers:'',
totalApplication:'',
chartData:{},
newuserstoday:'',
candidatesOnliveAdvt:'',
totalsignuptilltoday:'',
genderDetails:{
male:'',
female:'',
other:''
}
}
}
componentDidMount(){
const newChartData = {...this.state.chartData}
let url4 ="http://localhost:7080/getGenderAgainstAdvt";
getAllData(url4).then(
response => this.setState({genderDetails:response.data},()=>{
console.log("male gender count: "+this.state.genderDetails.male);
console.log("female gender count: "+this.state.genderDetails.female);
console.log("other gender count: "+this.state.genderDetails.others);
})
);
}
componentWillMount(){
this.getChartData();
}
getChartData(){
// Ajax calls here
let maleCount = this.state.genderDetails.male;
let femaleCount = this.state.genderDetails.female;
let otherCount = this.state.genderDetails.other;
console.log("male count is " +maleCount);
this.setState({
chartData:{
labels: ['Male', 'Female', 'Other'],
datasets:[
{
label:'Population',
data:[
maleCount,femaleCount,otherCount
],
backgroundColor:[
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)'
],
borderWidth:1,
hoverBorderWidth:3,
hoverBorderColor:'green'
}
]
}
});
}
render(){
return(
<div>
<div className="container">
<div className="row" style={border}>
<div className="col-sm-8">
<Chart chartData={this.state.chartData}/>
</div>
</div>
</div>
</div>
);
}
}
export default ScreenView;
和我的其他组件图表如下所示: -
class Chart extends Component {
constructor(props){
super(props);
this.state = {
chartData:props.chartData
}
//console.log("chart data is here...."+ props.chartData.datasets[0].data[0].male);
}
static defaultProps = {
displayTitle:true,
displayLegend: true,
legendPosition:'right',
location:'16530-16536/2074-75'
}
render(){
return (
<div className="chart">
<Pie
data={this.state.chartData}
options={{
title:{
display:this.props.displayTitle,
text:'Pie Chart for Advertisement Code '+this.props.location,
fontSize:25
},
legend:{
display:this.props.displayLegend,
position:this.props.legendPosition
}
}}
/>
</div>
)
}
}
我的API返回非常简单的JSON,如下所示: -
{
"male": 74433,
"female": 51442,
"others": 183
}
我需要获取此API数据并根据它绘制饼图。我的问题是我无法将API返回的数据发送到图表数据集。
如果我将一些手工数据发送到图表,即
datasets:[
{
label:'Population',
data:[
12345,54758,2154
],
}]
然后它成功绘制数据。但是现在我必须使用API获取数据而不是手动插入数据。我怎么能这样做?
更新: -
我的图表组件未接收数据。所以我将this.state.chartData
更改为this.props.chartData
并将其改为一半。从某种意义上讲,我现在能够绘制图表,但它只绘制了三个中的两个给定值。
请看照片。
答案 0 :(得分:1)
直接使用道具数据来渲染图表:
<Pie
data={this.props.chartData}
...
...
每当您的父ScreenView
获取新数据时,该数据将被发送到子Chart
组件并重新呈现