【问题标题】:Create Pie Chart Using JSON Data React使用 JSON 数据 React 创建饼图
【发布时间】:2021-12-14 10:55:57
【问题描述】:

我有一个数组,由一个名为 Status 的键组成,它有两个值 1 是好的,另一个是坏的我正在使用 react-google-charts 我在下面上传我的代码,请检查并帮助我

JSON:

[
    {
        Status: 'Good'
    },
    {
        Status: 'Bad'
    },
    {
        Status: 'Bad'
    },
    {
        Status: 'Good'
    },
    {
        Status: 'Good'
    },
    {
        Status: 'Bad'
    },
    {
        Status: 'Good'
    }
]

我的反应代码:

import React from 'react';
import Chart from 'react-google-charts';
import axios from 'axios';

export default class chart extends Component {
    constructor() {
        super();
        this.state = {
            items: []
        };
    }

    componentDidMount() {
        axios.get('http://localhost:5000/items').then(response => this.setState({ items: response.data }));
    }

    render() {
        return (
            <div>
                <Chart
                    width={'500px'}
                    height={'300px'}
                    chartType="PieChart"
                    loader={<div>Loading Chart</div>}
                    data={[['Task', 'Status of Items'], ['Good', 4], ['Bad', 3]]}
                    options={{
                        title: 'Item Status'
                    }}
                    rootProps={{ 'data-testid': '1' }}
                />
            </div>
        );
    }
}

目前我在这里对值进行了硬编码:

    data={[
        ['Task', 'Status of Items'],
        ['Good', 4],
        ['Bad', 3],
      ]}

我想使用 API 在上面的代码中添加好与坏的编号,我尝试查找数组的长度,但它不起作用,它发现整个数组的值既不好也不坏。请帮助我

【问题讨论】:

    标签: reactjs charts react-google-charts


    【解决方案1】:

    首先,您可以reduceGoodBad 计数归为一个 JSON,然后使用 Object.entries 获得所需的格式,如下所示一个数组。

    这样试试

    <Chart
        width={'500px'}
        height={'300px'}
        chartType="PieChart"
        loader={<div>Loading Chart</div>}
        data={[
            ['Task', 'Status of Items'],
            ...Object.entries(
                this.state.items.reduce((prevValue, currValue) => {
                    prevValue[currValue.Status] =
                        prevValue[currValue.Status] === undefined ? 1 : prevValue[currValue.Status] + 1;
                    return prevValue;
                }, {})
            )
        ]}
        options={{
            title: 'Item Status'
        }}
        rootProps={{ 'data-testid': '1' }}
    />
    

    代码沙箱 => https://codesandbox.io/s/busy-wind-1bizj?file=/src/App.js

    【讨论】:

    • @Karthikeyan M,看看这个!!
    • 非常感谢它有效! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2016-11-02
    • 1970-01-01
    相关资源
    最近更新 更多