如何在highcharts中从setInterval函数获取react useState挂钩的更新值? [英] how to get updated value of react useState hook from setInterval function in highcharts?

查看:88
本文介绍了如何在highcharts中从setInterval函数获取react useState挂钩的更新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()变量的更新值

Hi, I'm doing with a next js project.

I need to add the highcharts graph in my project.
I want to get the data from api & push it to setCount hook. but, I'm getting problem.. whenever I want to get the value of count hook in chart.series[0].addPoint([new Date().getTime(), count],true) but i can't able to get the updated value from my hook. I can't get the updated value of const [count, setCount] = useState() variable from

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中获取更新的值.

I think, I'm getting This problem because of setInterval function.. but setInterval is important, else how can I push data to chart.series[0].addPoint with interval.
How can i get the updated value in every setInterval.

请帮助我.

推荐答案

请检查有关 useState 中的值的详细说明:

Please check this great explanation about values in useState: https://stackoverflow.com/a/58877875

2个渲染之间的值可能有所不同,但保持不变在渲染本身内部和任何闭包内部(存在的功能即使在渲染完成后也可以更长一些,例如useEffect,事件处理程序,在任何Promise或setTimeout中).

The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect, event handlers, inside any Promise or setTimeout).

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

As a solution use addPoint method in the same function where you recieve data.

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>
  );
}


实时演示: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆