谁能帮助我从JSON文件向Chart.js条形图获取正确的数据。我可以访问JSON文件,并且工作正常。我似乎在为Chart.js标签,数据集和选项映射正确的JSON层次结构/对象时遇到问题。我在没有帮助的情况下尝试使用JSONdata.barchart.labels.map查找标签。
React组件:
import React from "react";
import Layout from "./Layout";
import { Grid, Header, Statistic } from "semantic-ui-react";
import JSONdata from "../data/DashboardData.json";
import { Bar } from "react-chartjs-2";
const DashboardBarChart = () => {
const data = {
labels: [JSONdata.barChart.map(item => item.labels)],
datasets: [JSONdata.barChart.map(item => item.datasets)],
options: [JSONdata.barChart.map(item => item.options)]
};
return <Bar data={data} />;
};
export default class Dashboard extends React.PureComponent {
renderDashboardStatistics = () => {
return JSONdata.statistics.map(item => {
return (
<Statistic key={item.id}>
<Statistic.Value>{item.value}</Statistic.Value>
<Statistic.Label>{item.id}</Statistic.Label>
</Statistic>
);
});
};
render() {
return (
<Layout {...this.props}>
<Header as="h2">Dashboard</Header>
<Grid stackable>
<Grid.Row>
<Grid.Column width={16}>
<Header as="h4" dividing>
Monthly users
</Header>
<DashboardBarChart />
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={16}>
<Header as="h4" dividing>
Statistics
</Header>
<Statistic.Group size="small">
{this.renderDashboardStatistics()}
</Statistic.Group>
</Grid.Column>
</Grid.Row>
</Grid>
</Layout>
);
}
}
JSON文件:
{
"barChart": [
{
"labels": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
},
{
"datasets": [
{
"label": "Monthly users",
"backgroundColor": "rgba(255,99,132,0.2)",
"borderColor": "rgba(255,99,132,1)",
"borderWidth": 1,
"hoverBackgroundColor": "rgba(255,99,132,0.4)",
"hoverBorderColor": "rgba(255,99,132,1)",
"data": [65, 59, 80, 81, 56, 55, 40, 65, 59, 80, 81, 56]
}
]
},
{
"options": {
"scales": {
"yAxes": [
{
"ticks": {
"beginAtZero": true
}
}
]
},
"layout": {
"padding": {
"left": 0,
"right": 0,
"top": 0,
"bottom": 0
}
},
"legend": {
"display": false
}
}
}
],
答案 0 :(得分:1)
我不确定图表上是否需要数据结构,但是我认为您可以删除JSONdata
和map
周围的方括号;而是直接直接访问属性,例如
labels: JSONdata.barChart[0].labels,
datasets: JSONdata.barChart[1].datasets,
options: JSONdata.barChart[2].options