我正在从Axio的http请求加载一个json。 React无法将对象传递到状态,因此我将它们转换为两个数组。 我想取数组并将它们注入
myChart = {
data: {
labels: getLabels(),
和
myChart = {
data: {
datasets: [{
data: getData(),
我不确定我想要做什么,这是某种类型的绑定方法吗?
import axios from "axios";
import React, { Component } from "react";
var LineChart = require("react-chartjs").Line;
class Graph extends Component {
constructor(props) {
super(props);
this.state = { mode: undefined } ;
}
getInitialState() {
return {
rates: []
}
}
componentDidMount() {
var jsonLoc = "http://api.fixer.io/latest?base=USD";
axios
.get(jsonLoc)
.then(res => {
var jsonObject = res.data;
console.log(jsonObject.rates);
var keyArray = [];
var valueArray = [];
var object = jsonObject.rates;
for (var prop in object){
keyArray.push(prop);
valueArray.push(object[prop]);
}
console.log(keyArray);
console.log(valueArray);
this.setState({ label: keyArray })
this.setState({ data: valueArray })
}
)
.catch(err => console.log(err))
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
function getLabels(){
return [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
}
function getData(){
return [1232, 2321, 15333,4020, 6043, 12313, 5453, ];
}
var myChart = {
type: "line",
data: {
labels: getLabels(),
datasets: [{
label: "Graph1",
data: getData(),
fillColor: "rgba(151,187,205,0.3)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
}]
},
options: {
"showScale" : true, //grid and scale numbers
"showTooltips" : true,
"responsive" : true,
"maintainAspectRatio" : false,
"pointDot" : true,
"bezierCurve" : true,
"datasetFill" : true,
"animation" : true,
"barShowStroke" : false,
"barStrokeWidth" : 1,
"barValueSpacing" : 1,
"barDatasetSpacing" : 1,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
};
return (
<div>
<div>
<LineChart ref="chart" data={myChart.data} options={myChart.options} width="600" height="250"/>
{this.state.label}
{this.state.data}
</div>
</div>
);
}
}
export default Graph;