如何在 Reactjs 中将服务器端 Json 数据转换为 react-google-chart 格式
How to convert server side Json data into react-google-chart format in Reactjs
我的后端有以下输出
[
{
"_id": null,
"counts": [
{
"department": "Cleaning",
"number": 1
},
{
"department": "Engineering",
"number": 2
},
{
"department": "Transportation",
"number": 1
}
]
}
]
我想将以下数据转换成 google 图表格式,然后在 reactjs 中将其显示在饼图上。
这是我第一次使用google-图表,我真的不知道如何进行转换。
根据我在网上阅读的内容,我实际上可以做这样的事情
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);
})
}
如果是这种情况,那么我的另一个挑战将是如何利用 google 图表中的新状态 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,
}}
如有任何帮助,我将不胜感激。
下面是一些示例状态,应该如下所示:
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
我的后端有以下输出
[
{
"_id": null,
"counts": [
{
"department": "Cleaning",
"number": 1
},
{
"department": "Engineering",
"number": 2
},
{
"department": "Transportation",
"number": 1
}
]
}
]
我想将以下数据转换成 google 图表格式,然后在 reactjs 中将其显示在饼图上。
这是我第一次使用google-图表,我真的不知道如何进行转换。 根据我在网上阅读的内容,我实际上可以做这样的事情
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);
})
}
如果是这种情况,那么我的另一个挑战将是如何利用 google 图表中的新状态 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,
}}
如有任何帮助,我将不胜感激。
下面是一些示例状态,应该如下所示:
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