import React,{PropTypes, Component} from "react";
import "./css/graphs.scss";
import ReactEcharts from 'echarts-for-react';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/tooltip';
import {Card, Radio} from 'antd';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
export default class Graphs extends React.Component {
constructor() {
super();
this.state = {
graphsData: []
};
};
componentWillUnmount() {
var myHeaders = new Header();
myHeaders.append("Content-Type", "application/json; charset=UTF-8");
myHeaders.append("Content-Length", context.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
var myInit = {
method: 'POST',
headers: myHeaders,
mode: 'cors',
cache: 'default'
}; // 头部信息,解决兼容性问题
var url = "http://localhost:3000/users/data"; // 接口url
fetch(url).then(function(res) {
if (res.ok) {
console.log(res.json());
return res.json()
} else {
{
this.LogError(res)
}
}
}).then(function(json) {
if (json.code == "200") {
return json.data
}
}).then(function(data) {
for (var i = 0; i < data.length; i++) {
return data[i]
}
}).then((e) => {
this.setState({graphsData: e})
})
}
LogError(res) {
console.error('服务器繁忙,请稍后重试; \r\nCode:' + res.status)
}
getOption() {
return {
color: ['#ff6384'],
title: {
// text: '动态数据',
// subtext: '纯属虚构'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#ff6384'
}
}
},
legend: {
data: ['最新电量']
},
toolbox: {
show: false,
feature: {
dataView: {
readOnly: false
},
restore: {},
saveAsImage: {}
}
},
dataZoom: {
show: false,
start: 0,
end: 100
},
xAxis: [
{
type: 'category',
boundaryGap: true,
data: (function() {
var now = new Date();
var res = [];
var len = 10;
while (len--) {
res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''));
now = new Date(now - 1800000);
}
return res;
})()
}, {
type: 'category',
boundaryGap: true,
data: (function() {
var res = [];
var len = 10;
while (len--) {
res.push(len + 1);
}
return res;
})()
}
],`请输入代码`
yAxis: [
{
type: 'value',
scale: true,
name: '电量',
max: 30,
min: 0,
boundaryGap: [0.2, 0.2]
}, {
type: 'value',
scale: true,
name: '计划电量',
max: 1200,
min: 0,
boundaryGap: [0.2, 0.2]
}
],
series: [
{
name: '最新电量',
type: 'line',
data : 我这里要后台给的数据
},
]
};
}
render() {
return (
<Card id="dash-graph" title="空压机能耗曲线" extra={< div > <RadioGroup defaultValue="a">
<RadioButton value="a">时</RadioButton>
<RadioButton value="b">天</RadioButton>
<RadioButton value="c">月</RadioButton>
</RadioGroup> < /div>}>
<div >
<ReactEcharts option={this.getOption()} notMerge={true} lazyUpdate={true} theme={"theme_name"}/>
</div>
</Card>
);
};
}
以上是我自己胡乱写的,关键就在series的data,我不知道怎么搞数据,我后台模拟了一个假个数据,是个json格式的,里面一个data:[1,2,4,5,3,2]这样的一个数组。
有没有人能解决一下,我series里data数据怎么从后台返回的写进去啊。
getOption()方法return的对象,直接写到this.state.option上,render函数中:
拿到后台数据后,直接通过this.setState({option: <data.res>})改变参数,然后视图就自动更新了