使用异步对象数据在React中绘制图表



我正在尝试使用从API获取的数据制作图表,但我遇到的问题是,由于对数据进行异步调用,我无法正确呈现图表。我相信图表在填充数据之前就已经执行了,因为加载窗口时,没有任何东西可以渲染。然而,当我尝试在数据变量中硬编码值来代替"时间戳"one_answers"价格"时,图表立即呈现出来。有人知道我如何格式化代码的其余部分,以便只有在填充了时间戳和价格数组后才能显示图表吗?

import { useEffect } from 'react';
import { Line } from 'react-chartjs-2';
const MarketAPI = require('market-api');
const Client = new MarketAPI();
function GRAPH(){
const timestamps = [];
const prices = [];
var getData = async() => {
const fromTS = (Date.now() / 1000 | 0 ) - 86400; // 1D from current timestamp
const toTS = Date.now() / 1000 | 0; // current timestamp
let get = await Client.assets.fetchAssetHist('MSFT', {
from: fromTS,
to: toTS,
});
for(let i = 0; i < get.data.prices.length; i++){
timestamps.push(get.data.prices[i].[0]);
prices.push(get.data.prices[i].[1]);
}
console.log(timestamps);
console.log(prices);
}
const data =  {
labels: timestamps,
datasets: [
{
data: prices,
fill: true,
backgroundColor: 'rgba(243, 230, 200, 0.2)', 
borderColor: 'rgba(243, 210, 18)', 
},
],
};
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false
},
display:true
},
y: {
grid: {
display: false
},
display: false
}
},
elements: {
point:{
radius: 0
}
},
};
useEffect(()=>{
getData()
},[]);
return(
<div>
<Line data={data} options={options}/>
</div>
);
}
function App() {
return (
<GRAPH/>
);
}

使用useState Hook来存储数据。

import { useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
const MarketAPI = require('market-api');
const Client = new MarketAPI();
function GRAPH(){
const timestamps = [];
const prices = [];
const [data, setData] = useState({})
var getData = async() => {

const fromTS = (Date.now() / 1000 | 0 ) - 86400; // 1D from current timestamp
const toTS = Date.now() / 1000 | 0; // current timestamp
let get = await Client.assets.fetchAssetHist('MSFT', {
from: fromTS,
to: toTS,
});
for(let i = 0; i < get.data.prices.length; i++){
timestamps.push(get.data.prices[i].[0]);
prices.push(get.data.prices[i].[1]);
}
console.log(timestamps);
console.log(prices);
}
setData({
labels: timestamps,
datasets: [
{
data: prices,
fill: true,
backgroundColor: 'rgba(243, 230, 200, 0.2)', 
borderColor: 'rgba(243, 210, 18)', 
},
],
})

const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false
},
display:true
},
y: {
grid: {
display: false
},
display: false
}
},
elements: {
point:{
radius: 0
}
},
};
useEffect(()=>{
getData()
},[]);
return(
<div>
<Line data={data} options={options}/>
</div>
);
}
function App() {
return (
<GRAPH/>
);
}

最新更新