【问题标题】:how to get updated value of react useState hook from setInterval function in highcharts?如何从 highcharts 中的 setInterval 函数获取 react useState 钩子的更新值?
【发布时间】: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


    【解决方案1】:

    请查看关于useState 中值的精彩解释:https://stackoverflow.com/a/58877875

    两次渲染之间的值可能不同,但保持不变 在渲染器本身和任何闭包内(存在的函数 即使在渲染完成后更长,例如useEffect,事件处理程序, 在任何 Promise 或 setTimeout 中)。

    作为一种解决方案,在您接收数据的同一函数中使用addPoint 方法。

    function App() {
      const [count, setCount] = useState();
      const chartComponent = useRef(null);
      const [options] = useState({...});
    
      useEffect(() => {
        const interval = setInterval(async () => {
          const res = await fetch(
            "https://socialcounts.herokuapp.com/https://socialcounts.in/api/random-num"
          );
    
          const data = await res.json();
          if (chartComponent.current) {
            chartComponent.current.chart.series[0].addPoint(
              [new Date().getTime(), data["num"]],
              true
            );
          }
    
          setCount(data["num"]);
        }, 2000);
    
        return () => clearInterval(interval);
      }, []);
    
      return (
        <center>
          <h1>{count}</h1>
          <HighchartsReact
            ref={chartComponent}
            highcharts={Highcharts}
            options={options}
          />
        </center>
      );
    }
    

    现场演示: https://codesandbox.io/s/highcharts-react-demo-forked-x9xi9?file=/demo.jsx

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2021-05-23
      • 1970-01-01
      • 2021-03-25
      • 2021-08-24
      相关资源
      最近更新 更多