使用ChartJs在ReactJs中进行数据可视化 [英] Data visualization in ReactJs with ChartJs
本文介绍了使用ChartJs在ReactJs中进行数据可视化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是reactjs的新手.目前,我正在开发一个应用程序,使用chartjs将JSON COVID-19 api数据显示为可视化.我从昨天开始尝试过,但是无法显示视觉数据.
I am new in reactjs. Currently I'm developing an app which shows json COVID-19 api data into visualization using chartjs. I tried this from yesterday but I can't show the visual data.
这是我的代码
App Component
import React, { useState, useEffect } from "react";
import axios from "axios";
import Chart from "./Chart";
const App = () => {
const [state, setState] = useState({});
const [loading, setLoading] = useState(true);
const [chart, setChart] = useState({});
useEffect(() => {
getData("italy");
setChart({
labels: ["Cases", "Deaths", "Recovered"],
datasets: [
{
label: "cases",
data: [state.cases]
},
{
label: "deaths",
data: [state.deaths]
},
{
label: "recovered",
data: [state.recovered]
}
]
});
}, []);
const getData = async country => {
try {
const res = await axios.get(
`https://corona.lmao.ninja/v2/historical/${country}`
);
setLoading(false);
setState(res.data.timeline);
} catch (error) {
console.log(error.response);
}
};
return (
<div>
{!loading
? console.log(
"cases",
state.cases,
"deaths",
state.deaths,
"recovered",
state.recovered
)
: null}
{!loading ? <Chart chart={chart} /> : "loading failed"}
</div>
);
};
export default App;
And Here is Chart Component
import React from "react";
import { Line } from "react-chartjs-2";
const Chart = ({chart}) => {
return (
<div>
<Line
data={chart}
height={300}
width={200}
options={{
maintainAspectRatio: false,
title: {
display: true,
text: "Covid-19",
fontSize: 25
},
legend: {
display: true,
position: "top"
}
}}
/>
</div>
);
};
export default Chart;
如果我打开浏览器并使用开发工具,它看起来像这样
If I open browser and dev tools it look likes this
我想像这样可视化数据
Here is codeSandBox.io
推荐答案
看起来像数据集中的data属性仅采用数字数组.我已经使用基于类的组件简化了您的代码.它将帮助您入门.
Looks like data property within dataset takes only array of numbers. I have simplifies your code using class based component. It will help you get started.
https://codesandbox.io/s/react-chartjs-2-example-mzh9o
setChartData = () => {
let { data } = this.state;
let chartData = {
labels: ["Cases", "Deaths", "Recovered"],
datasets: [
{
label: "cases",
data: Object.values(data.cases)
},
{
label: "deaths",
data: Object.values(data.deaths)
},
{
label: "recovered",
data: Object.values(data.recovered)
}
]
};
this.setState({
chart: chartData
});
};
这篇关于使用ChartJs在ReactJs中进行数据可视化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文