【发布时间】:2021-02-25 20:10:54
【问题描述】:
import Error from 'next/error'
import React, { useState, useEffect } from 'react'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
function id() {
const [count, setCount] = useState()
const options = {
chart: {
renderTo: 'chart',
type: 'spline',
zoomType: 'x',
backgroundColor: 'transparent',
plotBorderColor: 'transparent',
events: {
load: function () {
const chart = this
setInterval(function () {
chart.series[0].addPoint([new Date().getTime(), count], true)
}, 1000);
}
}
},
title: {
text: 'Chart'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 200,
gridLineColor: "red",
labels: {
style: {
color: "red"
}
},
lineColor: "red",
minorGridLineColor: 'red',
tickColor: "red",
title: {
style: {
color: "red"
}
}
},
yAxis: {
title: {
text: ''
},
gridLineColor: "red",
labels: {
style: {
color: "red"
}
},
lineColor: "red",
minorGridLineColor: 'red',
tickColor: "red"
},
credits: {
enabled: false
},
series: [{
name: "Random Number"
}]
}
useEffect(() => {
const interval = setInterval(async () => {
const res = await fetch("https://socialcounts.herokuapp.com/https://socialcounts.in/api/random-num")
const data = await res.json()
setCount(data["num"])
}, 1000);
return () => clearInterval(interval);
}, [])
return (<center>
<h1>{count}</h1>
<p></p>
<HighchartsReact highcharts={Highcharts} options={options} />
</center>)
}
export default id
嗨,
我正在做下一个 js 项目。
我需要在我的项目中添加 highcharts 图表。
我想从 api 获取数据并将其推送到 setCount 挂钩。
但是,我遇到了问题..
每当我想在chart.series[0].addPoint([new Date().getTime(), count],true) 中获取count 钩子的值时,但我无法从我的钩子中获取更新的值。
我无法从中获取const [count, setCount] = useState() 变量的更新值
events: {
load: function () {
const chart = this
setInterval(function () {
chart.series[0].addPoint([new Date().getTime(), count], true)
}, 1000);
}
}
我想,由于 setInterval 函数,我遇到了这个问题。
但 setInterval 很重要,否则我如何将数据推送到 chart.series[0].addPoint 与间隔。
如何获取每个 setInterval 中的更新值。
请帮帮我..
【问题讨论】:
标签: javascript reactjs highcharts next.js setinterval