Google图表无法正确呈现-反应JS

时间:2019-03-15 04:05:12

标签: javascript arrays reactjs api charts

我是React js的新手。我的要求是基于api响应生成图。我正在使用Google图表生成图表。请找到代码

import React from "react";
import PropTypes from 'prop-types';
import MonitoringDashboardAPI from "../utils/apis/MonitoringDashboardAPI";
import {HTTPStatus} from "../utils/Constants";
import Chart from "react-google-charts";

const cpuMetaData = {names: ['Time', 'System CPU'], types: ['time', 'linear']};
const cpuLineChartConfig = {
    x: 'Time',
    charts: [{type: 'line', y: 'System CPU', style: {markRadius: 2}}],
    gridColor: '#FF0000',
    tipTimeFormat: "%M:%S %Z",
    style: {
        axisLabelColor: '#9c9898',
        legendTitleColor: '#9c9898',
        legendTextColor: '#9c9898',
        tickLabelColor: '#f2f2f2',
    }
};

const styles = {
    root: {display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around'},
    gridList: {height: '50%', overflowY: 'auto', padding: '0 10px', margin: '-10px 0'}
};

const options = {
    title: "Company Performance",
    curveType: "function",
    legend: { position: "bottom" }
};

export default class Dashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isApiCalled: false,
            cpu: [],
            memUsage: [],
            test:[],
            //statusMessage: this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'Currently metrics are not available'}),
            isError: false,
            pInterval: 1000,
            interval: 1000
        };
        //this.renderWorkers = this.renderWorkers.bind(this);
         this.renderCPUChart = this.renderCPUChart.bind(this);
    }

    initAutoSync() {
        let interval = '';
        let that = this;
        let queryParams = {
            params: {
                period: '5sec'
            }
        };

        interval = setInterval(() => {
            // that.setState({currentTime: new Date().getTime()});
            MonitoringDashboardAPI.getSystemDetails()
                .then((response) => {
                  // this.state.memUsage.push(Math.floor(Date.now() / 1000),response.data.healthDeterminer.memoryUsage);
                    this.setState({
                        cpu: response.data.healthDeterminer.cpuUsage,
                        memUsage: response.data.healthDeterminer.memoryUsage,
                    });
                   // this.state.memUsage.push(response.data.healthDeterminer.memoryUsage)
                }).catch((error) => {
            });

        }, parseInt(this.state.pInterval));
        this.setState({interval: interval});

    }


    componentDidMount()
     {
       MonitoringDashboardAPI.getSystemDetails()
            .then((response) => {
                if (response.status === HTTPStatus.OK) {
                    this.setState({
                        cpu: response.data.healthDeterminer.cpuUsage,
                        memUsage: response.data.healthDeterminer.memoryUsage,
                        isApiCalled: true,
                        //   statusMessage: response.data === null ? this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'Currently metrics are not available'}) : ''
                    });
                }
            }).catch((error) => {
            if (error.response.status === 401) {
                this.setState({
                    isApiCalled: true,
                    //  statusMessage: this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'Authentication failed. Please login again'})
                });
            } else if (error.response.status === 403) {
                this.setState({
                    isApiCalled: true,
                    // statusMessage: this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'User have no permission to view this page'})
                });
            } else {
                this.setState({
                    isError: true,
                    isApiCalled: true,
                    //statusMessage: this.context.intl.formatMessage({id:'unknownError', defaultMessage: 'Unknown error occurred! : {data}', values: { data: JSON.stringify(error.response.data) } })
                });
            }
        });
        clearInterval(this.interval);
        this.initAutoSync();
        console.log(this.state.memUsage)
    }

    renderCPUChart() {
        return (
            <div style={{backgroundColor: '#131313', paddingTop: 10, height: '370px'}}>
                <div style={{backgroundColor: '#131313', paddingTop: 60, height: 255, width: '100%'}}>
                    <h1 style={{color: '#3366cc'}}>{this.state.memUsage} </h1>
                    <div className="App">
                        <Chart
                            chartType="LineChart"
                            width="100%"
                            height="400px"
                            data={[
                                ["Time stamp", "Memory Usage"],
                                [Math.floor(Date.now() / 1000), this.state.memUsage],
                            ]}
                            options={options}
                        />
                    </div>
                </div>
            </div>
        );
    }


    render() {
        console.log(this.state.cpu.length)
        return (
            this.renderCPUChart()
        );
    }
}
  

initAutoSync()方法用于在特定时间段内调用api。在此示例中,我每1秒调用一次api。

我的问题是,即使调用了API,memUsage数组也始终仅包含一个元素。但是该值正在根据API响应进行更新。基本上这些值不是附加值,而是覆盖值。因此,图表中只得到一个点。

请找到我的输出的屏幕截图

screenshot

1 个答案:

答案 0 :(得分:0)

尝试初始化componentDidMount ...

中的所有图表数据
this.setState({
    chartData: [
        ["Time stamp", "Memory Usage"],
        [Math.floor(Date.now() / 1000), response.data.healthDeterminer.memoryUsage],
    ],
    isApiCalled: true,
});

然后在间隔期间追加...

this.state.chartData.push([Math.floor(Date.now() / 1000), response.data.healthDeterminer.memoryUsage]);

和图表...

<Chart
    chartType="LineChart"
    width="100%"
    height="400px"
    data={this.state.chartData}
    options={options}
/>