微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在页面加载时发出 axios get 请求,然后使用该数据渲染 am4chart?

如何解决如何在页面加载时发出 axios get 请求,然后使用该数据渲染 am4chart?

我有最古怪的错误。就像……最古怪的!如果你们中的任何人想要关注这个,awesomesauce!我真的很欣赏它!我正在使用 REACT、Reduxsql、HML、Material-ui 和 CSS 创建调查。

我使用数据库中的数据通过 am4charts 创建了一个信息图表。一切正常,将显示页面上......但不是页面加载。我在控制台中看到的是页面将加载,它会触发我的 get 请求,但没有足够快地返回数据(我认为)。到 get 请求加载时,我的图表中已经没有数据了。

这是我要呈现的页面代码。真正奇怪的是,一旦我的代码运行完毕,我就可以剪切一行代码(我一直在使用控制台日志)。然后图形将呈现并加载。

import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";

import React,{ useRef,useState,useEffect } from 'react';
import axios from "axios";

function UnderstandingGraph(props) {
    
    const [Feedback,setFeedback] = useState('');    

    // ⬇ Creating the chart
    const chart = useRef(null);
    
    useEffect(() => {
        // ⬇ This calls my get request from the server
        getFeedback();
        // ⬇ This creates the kind of chart that I would like from am4charts
        let x = am4core.create("chartdiv",am4charts.XYChart);
        // ⬇ Padding to the right of the graph
        x.paddingRight =  20;
        // ⬇ This declares what kind of date format I would like.
        x.dateFormatter.dateFormat = "yyyy-MM-dd";
        // ⬇ Adding from the data that I set in the getFeedback function
        let data = dataArray;
        // ⬇ Making the data tied to the chart,called x.
        x.data = data;
        // ⬇ creating xAxes (the horizontal axis)
        let dateAxis = x.xAxes.push(new am4charts.DateAxis());
        // dateAxis.title.text = "Date";
        dateAxis.renderer.grid.template.location = 0;
        // ⬇ creating yAxes (the vertical axis)
        let valueAxis = x.yAxes.push(new am4charts.ValueAxis());
        valueAxis.tooltip.disabled = true;
        valueAxis.renderer.minWidth = 35;
        // ⬇ Creating the series for a line graph
        let series = x.series.push(new am4charts.Lineseries());
        // ⬇ Binding the data to the series
        series.datafields.dateX = "date";
        series.datafields.valueY = "understanding";
        series.tooltipText = "{valueY.value}";
        x.cursor = new am4charts.XYCursor();
        // ⬇ Scrollbar functionality at the top of the graph
        let scrollbarX = new am4charts.XYChartScrollbar();
        scrollbarX.series.push(series);
        x.scrollbarX = scrollbarX;

        chart.current = x;
        
        return () => {
            x.dispose();
        };
    },[]);

    // ⬇ This gets my data from the database and sets it to Feedback
    const getFeedback = ()  => {
        axios.get('/Feedback') 
        .then( (response) => {
            setFeedback(response.data)
        })
        .catch((error) => {
            console.log(`We have a server error`,error);
        });
    }

    //!! Want the graph to render? Cut nearly any line from this page,then the graph will force reload and show. Why?
    //! I have been copy/pasting line 71 to make the graph show.
    //! Interesting though,that when the page loads,I only see one console.log. When I re-paste it,I see two...
    //! It's almost like the computer can't think fast enough to get the data and then come back. Is there an async screen pause?
    console.log('Feedback',Feedback)
    
    // ⬇ Arrays of the data I will need:
    const dataArray = []
    // ⬇ Loops through Feedback 
    for (let i=0; i < Feedback.length; i++){
        // ⬇ Checking that I can get the dates that I want - I can!
        // console.log(Feedback[i])
        // console.log(Feedback[i].date) // Will log the long long date
        // console.log(Feedback[i].understanding) // Will log the number

        // ⬇ Makes an object,called data,that I can use to push into the dataArray.
        // Later we will use this to set the data points of the graph.
        let data = {
            "date": Feedback[i].date,"understanding": Feedback[i].understanding
        }
        dataArray.push(data)
    }

    

    return(
        <div id="chartdiv" style={{ width: "100%",height: "500px" }}></div>
    );
};

export default UnderstandingGraph;

我试图解决这个问题的方法

我尝试使用两个 useEffects,如下所示:

useEffect(() => {
        // ⬇ This calls my get request from the server
        getFeedback();
},[Feedback]);

useEffect(() => {
        // ⬇ Code for the graph here
},[]);

但出于某种古怪的原因,使我的服务器陷入无限循环。然后我尝试了:

useEffect(() => {
        // ⬇ This calls my get request from the server
        getFeedback();
},[]);

useEffect(() => {
        // ⬇ Code for the graph here
},[]);

图形将加载,我将在服务器端和浏览器中看到我的控制台日志...但我的图形中没有填充数据:(

如果有人想看,这就是我的服务器对我的数据库的请求以及数据库sql 数据。

//* GET REQUEST
// Will get all the responses
router.get('/',(req,res) => {
  let queryText = 'SELECT * from "Feedback" ORDER BY "date" ASC;'
  pool.query(queryText).then( result => {
    // ⬇ Sends back the results in an object
      res.send(result.rows);
      console.log('Result from server:',result.rows)
  }).catch( error => {
      console.log('Error GET',error);
      res.sendStatus(500);
  });
});
CREATE TABLE "Feedback" (
  "id" serial primary key,"feeling" INT not null,"understanding" INT not null,"support" INT not null,"comments" text,"flagged" boolean default false,"date" date not null default CURRENT_DATE
); 

-- Sample Data
INSERT INTO "Feedback" ("feeling","understanding","support","date")
VALUES 
(4,4,5,'2021-06-11'),(4,'2021-06-10'),2,'2021-06-9'),(2,'2021-06-7'),(1,3,'2021-06-4'),'2021-06-2'),(3,'2021-05-28'),'2021-05-26'),(5,'2021-05-25'),'2021-05-24'),'2021-05-21');

解决方法

你能试试这个修复吗?我为一些任务创建了新函数。

https://codesandbox.io/s/vigorous-varahamihira-6j588?file=/src/App.js

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。