[英]Parsing JSON Data to Chartjs in React
我一直通過 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;
Output:它只是顯示一個沒有數據的圖表
為了更好地理解這里是文檔的鏈接: 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"}}
將不勝感激您的幫助!
似乎問題出在 x 軸的類型上,因為如果您提供
datasets: [{
data: [{Date : '11',Close: 56},{Date : '22',Close: 656},{Date : '23',Close: 6}],
showLine: true,
fill: false,
borderWidth: 1,
parsing: {
xAxisKey: 'Date',
yAxisKey: 'Close'
},
backgroundColor: 'rgba(255, 99, 132, 1)'
}]
它畫得很好
所以你最好找到如何在 x 軸上顯示時間
我知道我遲到了,但我必須回答這個問題)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.