首先通过fetch获取后端数据后在前端进行输出,结果如下
{“state”:200,“data”:[{“id”:1,“name”:“短袖”,“price”:88.0,“sales”:600,“stock”:150,“detail”:“潮流时尚”},{“id”:2,“name”:“茶叶”,“price”:50.0,“sales”:500,“stock”:500,“detail”:“健康生活”},{“id”:3,“name”:“矿泉水”,“price”:2.0,“sales”:1000,“stock”:1000,“detail”:“大自然的馈赠”},{“id”:4,“name”:“香飘飘”,“price”:4.0,“sales”:200,“stock”:500,“detail”:“绕地球一周”},{“id”:5,“name”:“王老吉”,“price”:5.0,“sales”:400,“stock”:700,“detail”:“凉茶饮料”}]}
首先在react中通过fetch将后端数据库中的数据转化为JSON格式,然后通过JSON数据转化生成echarts表格
import React from 'react';
import ReactEcharts from 'echarts-for-react';
class Chartsbjw extends React.Component{
constructor() {
super()
this.state = {
blogPost: [],
finishedLoading: true
}
}
async componentDidMount() {
const response = await fetch('http://localhost:8080/goods')
const json = await response.json()
this.setState({ blogPost: json.data, finishedLoading: false })
}
reload = async () => {
const response = await fetch('http://localhost:8080/goods')
const json = await response.json()
this.setState({ blogPost: json.data, finishedLoading: true })
}
render(){
var data1 = new Array();
var data2 = new Array();
this.state.blogPost.map((blog,key)=>(
data1.push(blog.name)
))
this.state.blogPost.map((blog,key)=>(
data2.push(blog.price)
))
const option2={
title:{
text:'fetch动态获取后台数据绘制echarts图表'
},
color:['#db3347'], //调色盘颜色列表
tooltip:{ //提示框组件
trigger:'axis', //触发类型(坐标轴触发)
axisPointer:{
type:'line' //指示器类型(直线指示器)
}
},
grid:{ //直角坐标系内绘图网格
left:'3%', //grid组件离容器左侧的距离
right:'4%',
bottom:'3%',
containLabel:true //grid 区域是否包含坐标轴的刻度标签。
},
xAxis:[ //x轴
{
type:'category', //坐标轴类型(类目轴)
/*data:this.state.blogPost.map(function (item){
return item[1];
}), *///类目数据
data:data1,
axisTick:{ //坐标轴刻度相关配置
alignWithLabel:true //刻度线与标签对齐
},
axisLabel:{
color:'#ffffff'
},
},
],
yAxis:[
{
color:['#ffffff'],
type:'value', //数值轴
axisLabel:{
color:'#ffffff'
},
}
],
series:[ //系列列表
{
name:'直接访问',
type:'bar',
barWidth:'60%',
color:['#db3347'],
data:data2,
}
]
};
return(
<ReactEcharts
option={option2}
notMerge={true}
lazyUpdate={true}
style={{width: '100%',height:'100%'}}
/>
)
}
}
export default Chartsbjw;
注意该代码不可直接用,因为后端springboot的端口号不同,且mysql中的数据格式也不相同,只有操作流程相似。