ChartJS 如何在useEffect钩子中等待数据后再显示?

nkoocmlb  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(122)

所以我的问题很简单,我想,但我真的不知道如何解决它.
我试图在ChartJS折线图中显示一组数据,但检索数据时遇到问题。
API调用输出如下所示:

{
    "total": 4294496256,
    "valores": [
        {
            "time": "2022-06-01T07:00:00Z",
            "value": 2535383574.2608695
        },
        {
            "time": "2022-06-01T07:15:00Z",
            "value": 2544284512.711111
        },
        {
            "time": "2022-06-01T07:30:00Z",
            "value": 2537325454.2222223
        },
        {
            "time": "2022-06-01T07:45:00Z",
            "value": 2543294555.022222
        },
        {
            "time": "2022-06-01T08:00:00Z",
            "value": 2543005058.8444443
        },
        {
            "time": "2022-06-01T08:15:00Z",
            "value": 2548481774.9333334
        },
        {
            "time": "2022-06-01T08:30:00Z",
            "value": 2544248149.3333335
        },
        {
            "time": "2022-06-01T08:45:00Z",
            "value": 2543528618.6666665
        },
        {
            "time": "2022-06-01T08:56:06.1293542Z",
            "value": 2541892416
        }
    ]
}

我检索总值来设置y轴的最大值,我需要循环遍历所有“值”并将它们推送到数组中。
下面是用于useEffect调用的代码:

useEffect(() => {
    const getData = async () => {
      const res = await axios.get(
        "http://192.168.10.88:3000/test/memory?intervalo=1h&servidor=192.168.2.138&filtro=-1h"
      );
      const gbMaximo = Number(res.data.total / 1000 / 1000 / 1000);
      setMaximo(gbMaximo);
      let ejex = [];
      let valores = [];
      res.data.valores.map((valor) => {
        const tiempoFormateado = new Date(valor.time).toLocaleTimeString();
        ejex.push(tiempoFormateado);
        const gb = Number(valor.value) / 1000 / 1000 / 1000;
        const gbFinal = gb.toFixed(2);
        valores.push(gbFinal);
    });
    setLabels(ejex);
    setDatasets(valores);
    };

    getData()
  }, []);

其他一切都工作正常,但当我试图去网站,我只能看到2或3个值。
我的猜测是useEffect没有等待函数getData的完成,但是我真的不知道如何修复它,因为我不能让useEffect钩子运行一个异步函数。
谢谢你的帮助!

elcex8rz

elcex8rz1#

试试看:

useEffect(() => {
  const fetchData = async () => {
     const res = await axios.get(
      "http://192.168.10.88:3000/test/memory?intervalo=1h&servidor=192.168.2.138&filtro=-1h"
    );
     return res;
  }
  const getData = async () => {
    let res = await fetchData();
    const gbMaximo = Number(res.data.total / 1000 / 1000 / 1000);
    setMaximo(gbMaximo);
    let ejex = [];
    let valores = [];
    res.data.valores.map((valor) => {
      const tiempoFormateado = new Date(valor.time).toLocaleTimeString();
      ejex.push(tiempoFormateado);
      const gb = Number(valor.value) / 1000 / 1000 / 1000;
      const gbFinal = gb.toFixed(2);
      valores.push(gbFinal);
  });
  setLabels(ejex);
  setDatasets(valores);
  };

  getData()
}, []);

当然,您可以在useEffect之外定义函数

相关问题