javascript - 将 API 数据推送到 Chart.js
问题描述
我正在尝试将我的 API 数据推送到我的图表中,但数据更新时间与图表呈现时间似乎存在问题。我在 console.logging 我的两个数组,它没有显示数组中的任何内容。有谁知道在图表呈现该数据之前,我需要更改哪些内容才能将我的数据更新到状态?
function SmallBox(props) {
const [chartNums, setChartNums] = useState([])
const [chartLabels, setChartLabels] = useState([])
const [chartData, setChartData] = useState({})
const x = [];
const y = [];
const fetchData = async () => {
await fetch(`https://api.coingecko.com/api/v3/coins/${props.id}/market_chart?vs_currency=usd&days=1`)
.then((response) => {
return response.json();
})
.then((data) => {
for (let i = 0; i < data.prices.length; i++){
x.push(data.prices[i][0])
setChartLabels(x)
}
for (let i = 0; i < data.prices.length; i++){
y.push(data.prices[i][1])
setChartNums(y)
}
})
};
const chart = async () => {
await fetchData()
console.log(chartNums)
console.log(chartLabels)
setChartData({
labels: chartLabels,
datasets: [
{
label: '$',
data: chartNums,
backgroundColor: ['rgba(0,0,0,0.09)'],
borderColor: `${props.color}`,
borderWidth: 4,
borderJoinStyle: 'round',
borderCapStyle: 'round',
borderWidth: 3,
pointRadius: 0,
pointHitRadius: 10,
lineTension: .2,
}
]
})
}
useEffect(() =>{
chart();
}, []);
return (
<div id={props.id} className="smallBox">
<div className="smallBox_info">
<img className="smallBox-icon" src={props.image} alt={props.symbol}/>
<h2>{props.title}</h2>
</div>
<div className="smallBox_numbers">
<h2 className="smallBox-price">$ {props.currentPrice}</h2>
<h5 className="smallBox-roc">{props.percentChange}</h5>
</div>
<div className="smallBox_graph">
<Line data={chartData} options={{
responsive: true,
maintainAspectRatio: false,
title: {text: 'ThickBoyz', display: false},
legend: {display: false},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
scales: {
xAxes: [{
display: false,
gridLines: {}
}],
yAxes: [{
display: false,
gridLines: {}
}]
},
tooltips: {
callbacks: {
//This removes the tooltip title
title: function() {}
},
//this removes legend color
displayColors: false,
yPadding: 10,
xPadding: 10,
position: 'nearest',
caretSize: 10,
backgroundColor: 'rgba(255,255,255,.9)',
bodyFontSize: 15,
bodyFontColor: '#303030'
}
}}/>
</div>
</div>
)
}
export default SmallBox
解决方案
正确使用 async-await,不要将 promise then 方法与 await 混合使用。
import React, { useEffect, useState, useCallback } from "react";
import { Line } from "react-chartjs-2";
import "./styles.css";
export default function App() {
const [chartNums, setChartNums] = useState([]);
const [chartLabels, setChartLabels] = useState([]);
const [chartData, setChartData] = useState({});
const x = [];
const y = [];
const props = {
id: "bitcoin"
};
const fetchData = useCallback(async () => {
const response = await fetch(
`https://api.coingecko.com/api/v3/coins/${props.id}/market_chart?vs_currency=usd&days=1`
);
const data = await response.json();
if (data && data.prices) {
console.log(data.prices);
for (let i = 0; i < data.prices.length; i++) {
x.push(data.prices[i][0]);
setChartLabels(x);
}
for (let i = 0; i < data.prices.length; i++) {
y.push(data.prices[i][1]);
setChartNums(y);
}
}
}, [props]);
const chart = useCallback(async () => {
await fetchData();
console.log(chartNums);
console.log(chartLabels);
setChartData({
labels: chartLabels,
datasets: [
{
label: "$",
data: chartNums,
backgroundColor: ["rgba(0,0,0,0.09)"],
borderColor: `${props.color}`,
borderWidth: 4,
borderJoinStyle: "round",
borderCapStyle: "round",
pointRadius: 0,
pointHitRadius: 10,
lineTension: 0.2
}
]
});
}, [chartNums, chartLabels, fetchData, props.color]);
useEffect(() => {
chart();
}, [chart]);
return (
<div id={props.id} className="smallBox">
<div className="smallBox_info">
<img className="smallBox-icon" src={props.image} alt={props.symbol} />
<h2>{props.title}</h2>
</div>
<div className="smallBox_numbers">
<h2 className="smallBox-price">$ {props.currentPrice}</h2>
<h5 className="smallBox-roc">{props.percentChange}</h5>
</div>
<div className="smallBox_graph">
<Line
data={chartData}
options={{
responsive: true,
maintainAspectRatio: false,
title: { text: "ThickBoyz", display: false },
legend: { display: false },
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
scales: {
xAxes: [
{
display: false,
gridLines: {}
}
],
yAxes: [
{
display: false,
gridLines: {}
}
]
},
tooltips: {
callbacks: {
//This removes the tooltip title
title: function () {}
},
//this removes legend color
displayColors: false,
yPadding: 10,
xPadding: 10,
position: "nearest",
caretSize: 10,
backgroundColor: "rgba(255,255,255,.9)",
bodyFontSize: 15,
bodyFontColor: "#303030"
}
}}
/>
</div>
</div>
);
}
沙盒链接 - https://codesandbox.io/s/chartjs-fetchapidata-r3ghc?file=/src/App.js
推荐阅读
- ruby-on-rails - Rails:重复记录,一些关联,仅其他连接表
- php - 如何在codeigniter中做restful api更改密码?
- c - Visual Studio 2019 社区版可以强制执行严格的 ANSI C 合规性吗?
- python - 带有数字和大写字母的字符串的正则表达式匹配失败
- javascript - Javascript中的Sum Formatted Amount Money返回NaN
- jquery - 如何在元素单击时重置jquery ui滑块
- windows - 是否可以更改 docker 容器上的时间
- github-pages - Github 页面显示 404 File not found
- distributed-system - 一个典型的五台服务器集群如何能够容忍任何两台服务器的故障?
- azure-devops - Azure DevOps 服务器本地安装扩展通过 REST API