4

我的后端有以下输出

[
    {
        "_id": null,
        "counts": [
            {
                "department": "Cleaning",
                "number": 1
            },
            {
                "department": "Engineering",
                "number": 2
            },
            {
                "department": "Transportation",
                "number": 1
            }
        ]
    }
]

我想将以下数据转换为谷歌图表格式,然后将其显示在 reactjs 中的饼图上。

这是我第一次使用 google-charts,我真的不知道如何进行转换。根据我在网上阅读的内容,我实际上可以做这样的事情

class ChartPie extends React.Component {
state={
  data:[]
}
componentDidMount(){
  
axios.get(`/api/v1/employee/departCount`)
.then(({data}) => { // destructure data from response object
    // {department,number} from data
    const restructuredData = data.map(({department, number}) => 
        [department,number])

    this.setState({data: restructuredData});
})
.catch(function (error) {
  console.log(error);
})
}

如果是这种情况,那么我的另一个挑战将是如何利用谷歌图表 API 中的新状态

 render() {
    return (
      <div>
      <Chart
  width={'500px'}
  height={'300px'}
  chartType="PieChart"
  loader={<div>Loading Chart</div>}
  data={[
  
  // how do I add the new state ?
  ]}
  options={{
    title: 'Work data',
    is3D: true,
  }}

我将不胜感激任何帮助。

4

1 回答 1

0

这是一些示例状态应该如下所示:

const data = [
  ["Element", "Density", { role: "style" }],
  ["Copper", 8.94, "#b87333"], // RGB value
  ["Silver", 10.49, "silver"], // English color name
  ["Gold", 19.3, "gold"],
  ["Platinum", 21.45, "color: #e5e4e2"] // CSS-style declaration
];

您需要几个数组操作来创建正确的数据状态。工作示例:https ://codesandbox.io/s/react-google-charts-column-chart-forked-spjmz?file=/src/index.js:577-845

于 2020-12-26T09:01:42.137 回答