【发布时间】:2020-05-13 09:02:07
【问题描述】:
我正在使用反应 js。我想从我从 api 获取的数据中使用chartjs 制作图表。在这里,我只想在下面两个数组之间绘制图表。
symbolsdateforchart: []
closingdateforchart: []
但是,我不确定如何使用这些值(请查看我的代码),因为它还没有被分配,并且值在componentDidMount() 中分配,我在@987654324 中制作了我的图表@。有没有更好的方法在我提到的上述两个数组之间使用chartjs 制作图表。或者我可以以某种方式完成这项工作吗?任何帮助表示赞赏。
我的代码:
import React from "react";
import { Line } from "react-chartjs-2";
import Chart from "./Chart";
export default class Symbols extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
symbolsdateforchart: [],
closingdateforchart: [],
search: "",
symbol: this.props.location.symbol,
//here I am making my chart
chartData: {
labels: ["how to add the data of symbolsdateforchart here"], //and here I know the data is not yet assigned to symbolsdateforchart: [], so not sure how to make it work
datasets: [
{
label: "Closing price",
data: ["how to add the data of closingdateforchart here"], //and here I know the data is not yet assigned to closingdateforchart: [], so not sure how to make it work
fill: false,
backgroundColor: [
"rgba(255,99,132,0.6)",
"rgba(54,162,235,0.6)",
"rgba(255,206,86,0.6)",
"rgba(75,192,192,0.6)",
"rgba(153,102,255,0.6)",
"rgba(255,159,64,0.6)",
"rgba(255,99,132,0.6)",
],
},
],
},
};
}
componentDidMount() {
let symbolsdate = [];
let closingprice = [];
fetch(`http://131.181.190.87:3001/history?symbol=${this.state.symbol}`)
.then((res) => res.json())
.then((json) => {
console.log(json);
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
let tempclosingPrice = dataobj.close;
let tempArray = tempsymbolsDate.split("-");
tempsymbolsDate =
tempArray[2] + "/" + tempArray[1] + "/" + tempArray[0];
symbolsdate.push(tempsymbolsDate);
closingprice.push(tempclosingPrice);
}
this.setState({
isLoaded: true,
items: json,
//here the value get assigned for them
symbolsdateforchart: symbolsdate,
closingdateforchart: closingprice,
});
});
}
render() {
return (
//here I just print the table using the api I fetched in omponentDidMount()
);
}
}
【问题讨论】:
-
好吧,你不能从同一个对象访问构造函数中的数据,因为它还没有初始化,我建议在你的构造函数中将标签和数据作为空数组,然后在 componentDidMount更新状态时,只需更新图表中的标签和数据。
标签: reactjs api charts chart.js state