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

问题描述

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

我使用数据库中的数据创建了带有 am4charts 的信息图。一切正常,并将显示在页面上......但不是页面加载。我在控制台中看到的是页面将加载,它会触发我的获取请求,但返回数据的速度不够快(我认为)。到 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, 4, 5, '2021-06-10'),
(4, 2, 5, '2021-06-9'),
(2, 4, 5, '2021-06-7'),
(1, 3, 5, '2021-06-4'),
(4, 5, 5, '2021-06-2'),
(3, 3, 5, '2021-05-28'),
(3, 2, 5, '2021-05-26'),
(5, 4, 5, '2021-05-25'),
(2, 5, 5, '2021-05-24'),
(5, 5, 5, '2021-05-21');

标签: javascriptreactjsreduxam4maps

解决方案


你能试试这个修复吗?我为某些任务创建了新功能。

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


推荐阅读