Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Google图表未正确呈现_Javascript_Arrays_Reactjs_Api_Charts - Fatal编程技术网

Javascript Google图表未正确呈现

Javascript Google图表未正确呈现,javascript,arrays,reactjs,api,charts,Javascript,Arrays,Reactjs,Api,Charts,我是新手。我的需求是基于api响应生成图形。我正在使用谷歌图表生成图表。请找到密码 import React from "react"; import PropTypes from 'prop-types'; import MonitoringDashboardAPI from "../utils/apis/MonitoringDashboardAPI"; import {HTTPStatus} from "../utils/Constants"; import Chart from "reac

我是新手。我的需求是基于api响应生成图形。我正在使用谷歌图表生成图表。请找到密码

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()
        );
    }
}
从“React”导入React;
从“道具类型”导入道具类型;
从“./utils/api/MonitoringDashboardAPI”导入MonitoringDashboardAPI;
从“./utils/Constants”导入{HTTPStatus};
从“反应谷歌图表”导入图表;
常量cpuMetaData={名称:['Time',系统CPU'],类型:['Time',linear']};
常量cpuLineChartConfig={
x:‘时间’,
图表:[{type:'line',y:'systemcpu',style:{markRadius:2}}],
gridColor:“#FF0000”,
tipTimeFormat:“%M:%S%Z”,
风格:{
axisLabelColor:“#9c9898”,
legendTitleColor:“#9c9898”,
legendTextColor:“#9c9898”,
勾选颜色:'#f2f2f2',
}
};
常量样式={
根:{display:'flex',flexWrap:'wrap',justifyContent:'space around'},
gridList:{height:'50%',overflowY:'auto',padding:'0 10px',margin:'-10px 0'}
};
常量选项={
标题:“公司业绩”,
曲线类型:“函数”,
图例:{位置:“底部”}
};
导出默认类Dashboard扩展React.Component{
建造师(道具){
超级(道具);
此.state={
我说:错,
cpu:[],
memUsage:[],
测试:[],
//statusMessage:this.context.intl.formatMessage({id:'systemDetails',defaultMessage:'CurrentMetrics not available'}),
伊瑟罗:错,
平特瓦尔:1000,
间隔时间:1000
};
//this.renderWorkers=this.renderWorkers.bind(this);
this.renderCPUChart=this.renderCPUChart.bind(this);
}
initAutoSync(){
设区间=“”;
让那=这;
设queryParams={
参数:{
期间:“5秒”
}
};
间隔=设置间隔(()=>{
//setState({currentTime:new Date().getTime()});
MonitoringDashboardAPI.getSystemDetails()
。然后((响应)=>{
//this.state.memUsage.push(Math.floor(Date.now()/1000)、response.data.healthDeterminer.memoryUsage);
这是我的国家({
cpu:response.data.healthDeterminator.cpuUsage,
memUsage:response.data.healthDeterminator.memoryUsage,
});
//this.state.memUsage.push(response.data.healthDeterminator.memoryUsage)
}).catch((错误)=>{
});
},parseInt(this.state.pInterval));
this.setState({interval:interval});
}
componentDidMount()
{
MonitoringDashboardAPI.getSystemDetails()
。然后((响应)=>{
if(response.status==HTTPStatus.OK){
这是我的国家({
cpu:response.data.healthDeterminator.cpuUsage,
memUsage:response.data.healthDeterminator.memoryUsage,
艾萨克:没错,
//statusMessage:response.data==null?this.context.intl.formatMessage({id:'systemDetails',defaultMessage:'CurrentMetrics not available'}):“”
});
}
}).catch((错误)=>{
if(error.response.status==401){
这是我的国家({
艾萨克:没错,
//statusMessage:this.context.intl.formatMessage({id:'systemDetails',defaultMessage:'Authentication failed.Please Reuter登录'})
});
}else if(error.response.status==403){
这是我的国家({
艾萨克:没错,
//statusMessage:this.context.intl.formatMessage({id:'systemDetails',defaultMessage:'User无权查看此页面'})
});
}否则{
这是我的国家({
伊瑟罗:是的,
艾萨克:没错,
//statusMessage:this.context.intl.formatMessage({id:'UnknowError',defaultMessage:'发生未知错误!:{data}),值:{data:JSON.stringify(error.response.data)})
});
}
});
clearInterval(这个.interval);
this.initAutoSync();
console.log(this.state.memUsage)
}
renderCPUChart(){
返回(
{this.state.memUsage}
);
}
render(){
console.log(this.state.cpu.length)
返回(
这个是renderCPUChart()
);
}
}
initAutoSync()方法用于在特定时间段调用api。在本例中,我每1秒调用一次api

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

请找到我的输出截图


尝试初始化
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}
/>