我已成功将动态数据传递给React Chart JS 2,但我在显示它时遇到问题。 请查看附图的附件截图。
我试图为所有费用与月份制作折线图。如您所见,在屏幕截图的控制台中可以看到两个数组。一个是花费的金额,它花在相应的月份可以在它下面的数组中看到。例如:5月花了529,4月花了100。
这是我的Chart.js
import React from 'react';
import {connect} from 'react-redux';
import {Line} from 'react-chartjs-2';
import moment from 'moment';
const Chart = (props) => {
console.log(props.expenses);
const amount = props.expenses.map((expense) => {
// console.log(expense.amount);
// console.log(moment(expense.createdAt).format('MMMM'));
return expense.amount;
});
console.log(amount);
const createdAt = props.expenses.map((expense) => {
const arr_createdAt = expense.createdAt;
return moment(arr_createdAt).format('MMMM');
});
console.log(createdAt);
const data = {
labels: **createdAt**,
datasets: [
{
label: 'My First dataset',
fill: false,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: **amount**
}
]
};
return (
<div>
<div className = "page-header">
<div className = "content-container">
<h1 className = "page-header__title">CHART</h1>
</div>
</div>
<div className = "content-container">
<h2>Line Example</h2>
<Line data={data} />
</div>
</div>
)};
const mapStateToProps = (state) => {
return {
expenses : state.expenses
};
}
export default connect(mapStateToProps)(Chart);
我想要做的是将5月份花费的所有费用和5月份的总费用总额,以及其他月份的费用相同。
非常感谢任何帮助。 谢谢
答案 0 :(得分:0)
试试这个:
`let reducedValue = props.expenses.reduce((acc, item) => {
let index = acc.findIndex(accItem => moment(accItem.createdAt).format('MMM') === moment(item.createdAt).format('MMM'));
if(index < 0){
acc.push({...item});
} else {
acc[index].amount += item.amount;
}
return acc;
}, []);
let amount = reducedValue.map(item => item.amount);
let createdAt = reducedValue.map(item => moment(item.createdAt).format('MMM'));
`