简体   繁体   English

我将在哪里从我的数据库中获取数据以使用 react-chartjs-2 更新图表?

[英]Where would I fetch Data from my database to update a Chart Using react-chartjs-2?

I'm trying to create a Bar Chart with data I'm getting from my database.我正在尝试使用从数据库中获取的数据创建条形图。 Getting the data works fine, but updating the chart seems to be a problem.获取数据工作正常,但更新图表似乎是一个问题。 I'm trying to create a bar chart that gets my data, counts how many times each of the weekdays are presenst (the countData function) and then updates the state to reflect that in my Barchart.我正在尝试创建一个条形图来获取我的数据,计算每个工作日存在的次数(countData 函数),然后更新状态以在我的条形图中反映这一点。 Here's my file:这是我的文件:

import React, { useEffect, useState } from "react";
import $ from "jquery";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Bar } from "react-chartjs-2";
import { withRouter } from "react-router-dom";
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export default function Daily() {
  const [state, setState] = useState({
    monday: null,
    tuesday: null,
    wednesday: null,
    thursday: null,
    friday: null,
    saturday: null,
    sunday: null,
  });

  const [chartData, setChartData] = useState({
    datasets: [],
  });
  const [chartOptions, setChartOptions] = useState();


  useEffect(() => {
    fetch('http://php_spice.test/database_handler.php', {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      }
    }).then(async (response) => {
      let data = await response.json();
      data = data.result;
      data = countData(data);
      console.log(data);
      setState({
        monday: data["monday"],
        tuesday: data["tuesday"],
        wednesday: data["wednesday"],
        thursday: data["thursday"],
        friday: data["friday"],
        saturday: data["saturday"],
        sunday: data["sunday"],
      }); 

    }).catch((error) => {
      console.log('error: ' +error);
    })
    
    setChartData({
      labels: [
        "Montag",
        "Dienstag",
        "Mittwoch",
        "Donnerstag",
        "Freitag",
        "Samstag",
        "Sonntag",
      ],
      datasets: [
        {
          label: "e",
          data: [
            state.monday,
            state.tuesday,
            state.wednesday,
            state.thursday,
            state.friday,
            state.saturday,
            state.sunday,
          ],
        },
      ],
    });
    setChartOptions({
      responsive: true,
      plugins: {
        legend: {
          position: "top",
        },
        scales: {
          xAxes: [
            {
              ticks: {
                fontColor: "white",
              },
            },
          ],
        },
        title: {
          display: true,
          text: "eh",
        },
      },
    });
    
  }, []);

  return (
    <div className="Daily">
      <Bar data={chartData} options={chartOptions} />
    </div>
  );

  function doThing(){
    
  }

  function countData(resultData) {
    let monday = 0;
    let tuesday = 0;
    let wednesday = 0;
    let thursday = 0;
    let friday = 0;
    let saturday = 0;
    let sunday = 0;
    $.each(resultData, function (index, rd) {
      switch (rd) {
        case "0":
          monday++;
          break;
        case "1":
          tuesday++;
          break;
        case "2":
          wednesday++;
          break;
        case "3":
          thursday++;
          break;
        case "4":
          friday++;
          break;
        case "5":
          saturday++;
          break;
        case "6":
          sunday++;
          break;
      }
    });
    var countedDays = {
      monday: monday,
      tuesday: tuesday,
      wednesday: wednesday,
      thursday: thursday,
      friday: friday,
      saturday: saturday,
      sunday: sunday,
    };
    return countedDays;
  }
}

This is what my chart looks like on loading the page:这是我的图表在加载页面时的样子: 在此处输入图像描述

And this is the chart after saving my Daily.js in vscode:这是在 vscode 中保存 Daily.js 后的图表: 在此处输入图像描述

Only then the chart changes.只有这样图表才会改变。 I've added a dependency array to the useEffect Hook, because otherwise it would cause an infinite loop.我在 useEffect Hook 中添加了一个依赖数组,否则会导致无限循环。 I know this can be caused because of the setSate function in the useEfect hook, but I've already tried putting setstate, setChartData and setChartOptions in another function which is then called in fetch.我知道这可能是由于 useEfect 挂钩中的 setSate 函数引起的,但我已经尝试将 setstate、setChartData 和 setChartOptions 放在另一个函数中,然后在 fetch 中调用该函数。 That also didn't work.那也没用。

How will I be able to update my chart without causing an infinite loop?如何在不导致无限循环的情况下更新图表?

Maybe try somethink like:也许尝试一些像:

useEffect(()=>{
    const fetchData = async()=>{
      const data = await fetch('')
      const json = data.json()
      setState()
    }

    fetchData()
    .catch(console.error)
  },[])

The fetch will only in the first load execute.提取只会在第一次加载时执行。 When you wanna update every x minutes, then you should use a interval like this post: 当你想每 x 分钟更新一次时,你应该使用像这篇文章这样的间隔:

setChartData / setChartOptions are being called before the fetch request gathering the needed data has finished.在收集所需数据的获取请求完成之前调用setChartData / setChartOptions Try to move this logic into the success callback of your fetch call.尝试将此逻辑移动到fetch调用的成功回调中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM