首页 > 解决方案 > 在 React 中将 JSON 数据解析为 Chartjs

问题描述

我一直在通过 axios 从我的 MongoDB 服务器导入 JSON 文件。我能够成功获取数据,但无法在图表上显示。我已经看到了其他答案,似乎很容易将每个键列存储在一个单独的变量中,然后加载到labels对象data,但是这种更优化并且 Chartjs 也允许我们使用其文档中列出的这种方法,但我可能会在某个地方出错。需要帮助,因为我需要为我的项目实施它

import React, { useState } from 'react';
import axios from 'axios';
import { useEffect } from 'react';
import {Bar, Line} from 'react-chartjs-2';

const URL = process.env.REACT_APP_SERVER_URL || 'http://localhost:5000/';

function ChartRoughPage(props) {
    const [historicalData,setHistoricalData] = useState([]);

    useEffect(()=>{
        axios.get(URL+'stock/BLUEDART')
            .then((response)=>{
                if(response.status===200){   
                    console.log(response.data)
                    setHistoricalData(response.data)
                }
                else{
                    console.log("ERROR: "+response.status+" , "+response.statusText)
                }
            })
            .catch((err) => console.log.err);
    },[]);

    return (
        <div>
            <Line 
                data={{
                    datasets:[{
                        label:'Everyday Chart',
                        data : historicalData,
                        parsing:{
                            xAxisKey:'DATE',
                            yAxisKey:'CLOSE'
                        }
                    }]
                }}
            />
        </div>
    );
}

export default ChartRoughPage;

输出:它只显示一个没有数据的图表

为了更好地理解这里是文档的链接: https ://www.chartjs.org/docs/latest/general/data-structures.html

我还尝试在我的代码上进行以下操作:

...
            <Line 
                data={{
                    datasets:[{
                        data : historicalData
                    }]
                }}
                options={{
                    parsing:{
                        xAxisKey:'Date',
                        yAxisKey:'Close'
                    }
                }}
            />
...
historicalData = [{Date : '22-02-2000',Close: 56},{Date : '22-03-2000',Close: 656},{Date : '23-05-2000',Close: 6}]

我从MongoDB作为 JSON 发送的文档也是这样的(所有值都可以通过它们的键访问):

{"_id":{"$oid":"some-object-id"},"Date":"2019-01-03","Symbol":"20MICRONS","Series":"EQ","Prev Close":{"$numberDouble":"44.05"},"Open":{"$numberDouble":"44.05"},"High":{"$numberDouble":"44.1"},"Low":{"$numberDouble":"43.1"},"Last":{"$numberDouble":"43.4"},"Close":{"$numberDouble":"43.45"},"VWAP":{"$numberDouble":"43.48"},"Volume":{"$numberInt":"15741"},"Turnover":{"$numberDouble":"68447485000.0"},"Trades":{"$numberDouble":"368.0"},"Deliverable Volume":{"$numberInt":"9487"},"%Deliverble":{"$numberDouble":"0.6027"}}

将不胜感激您的帮助!

标签: javascriptreactjschart.jsreact-chartjs-2

解决方案


推荐阅读