这边我的数据传递是通过父穿子数据来更新chart图标,在同一个模块用接口获取数据同理
是通过对g2可视化的挂在和current属性来判断是否需要destroy操作
import { Chart } from '@antv/g2'
import React, { useEffect,useRef } from 'react'
const Temperature = (props) => {
const {data}= props
//重点
const chart = useRef()
useEffect(() => {
//判断是否有数据传递过来进行刷新
if(data){
getChart(data)
}
}, [data])
useEffect(()=>{
return () => {
if(chart.current){
chart.current.destroy()
}
}
},[])
const getChart =(data)=>{
if(!chart.current){
chart.current = new Chart({
container: 'temperature',
autoFit: true,
height: 180,
width: 480,
// width: 'auto',
})
}
const {current:_chart} = chart
_chart.clear()
_chart.data(data)
//下方配置就看个人需求,主要是改的是上面部分代码
_chart.scale('value', {
alias: 'mg/m³',
nice: true,
})
_chart.scale({
date: {
nice: true,
range: [0, 1],
},
value: {
// alias: '进入次数',
// min: 2,
// max: 6,
sync: true, // 将 合格率 字段数值同 废品率 字段数值进行同步
nice: true,
},
})
_chart.axis('value', {
grid: {
line: {
type: 'line',
style: {
// fill:'#ff0000',
stroke: '#482daf ',
// opacity:0.3,
// lineDash:[1,3],//虚线
},
},
},
label: {
style: {
fill: '#fff', //文字颜色
// fontFamily: "Microsoft YaHei",//文字字体
fontWeight: 400, //文字粗细
fontSize: 20, //文字大小
},
formatter: (text) => {
return text + '℃'
},
},
line: {
style: {
stroke: '#fff', //坐标轴颜色
},
},
})
_chart.axis('time', {
grid: {
line: {
type: 'line',
style: {
// fill:'#ff0000',
stroke: '#482daf ',
// opacity:0.3,
// lineDash:[1,3],//虚线
},
},
},
label: {
style: {
fill: '#fff', //文字颜色
// fontFamily: "Microsoft YaHei",//文字字体
// fontWeight: 400, //文字粗细
marginTop: 10,
fontSize: 20, //文字大小
},
},
line: {
style: {
stroke: '#fff', //坐标轴颜色
},
},
})
_chart.tooltip({
showMarkers: false,
})
_chart.line().shape('smooth').position('time*value').color('#01ffff')
_chart.interaction('element-active')
// 添加文本标注
data.forEach((item) => {
_chart.annotation().text({
position: [item.time, item.value],
content: item.value,
style: {
textAlign: 'center',
fill: '#fff',
fontSize: 20,
},
offsetY: -10,
})
})
_chart.render()
return _chart
}
return (
<div>
<div id="temperature"></div>
</div>
)
}
export default Temperature