如何在React中使用chart.js映射多个图表 [英] How to map multiple charts with chart.js in react
本文介绍了如何在React中使用chart.js映射多个图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我能够分别渲染每个图表,但是我不知道如何同时渲染多个图表.这是我的代码:
I am able to render each chart separately but I have no idea how to render multiple charts at the same time. Here is my code:
import React, { Component } from "react";
import {Line} from 'react-chartjs-2';
import axios from 'axios';
class Chart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: {},
data: []
}
}
componentDidMount() {
axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=2&page=1&sparkline=true')
.then(res => {
const x = res.data;
let y = [];
x.forEach(element => {
y.push(element.sparkline_in_7d.price)
})
console.log(y);
this.setState({
chartData: {
labels: y,
datasets:[{
data: y,
}
]
},
data: y
})
})
}
render() {
return (
<div className="chart">
//*WORKS*
{/* {this.state.data.map((n, index) => {
return (
<li key={index}>{n}</li>
);
})} */}
//*DOES NOT WORK*
{this.state.chartData.map((n, index) => {
return (
<Line key={index} data={n}/>
);
})}
</div>
);
}
}
export default (Chart);
通常我在映射数据时没有任何问题,但是在使用chartjs时遇到了问题,因为当我尝试使用它时,它说它不是一个函数.任何帮助,我们将不胜感激.
Normally I don't have any issues mapping data but I am having issues doing so with chartjs as when I try this it says it is not a function. Any help here would be appreciated.
推荐答案
chartData
应该是一个数组.
尝试以下方法.
//init state
this.state = {
chartData: [],
}
//service inside componentDidMount
axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=2&page=1&sparkline=true')
.then(res => {
const x = res.data;
let chartData = [];
x.forEach(element => {
chartData.push({
labels: element.sparkline_in_7d.price,
datasets:[{data: element.sparkline_in_7d.price}]
});
});
this.setState({chartData});
})
这是小提琴. https://codesandbox.io/s/sharp-wildflower-23hy7
希望它会对您有所帮助.
Hope it will helps you.
这篇关于如何在React中使用chart.js映射多个图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文