我使用的是react js。我想用 chartjs
从我从api中获取的数据。这里,我只是想在下面两个数组之间绘制图表。
symbolsdateforchart: []
closingdateforchart: []
但是,我不知道如何使用这两个数组的值(请看一下我的代码),因为它还没有被分配,而这个值是在 componentDidMount()
和我做我的图表里面 this.state
. 有没有更好的方法来制作图表,使用 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()
你可以更新状态变量 chartData
作为
this.setState({
isLoaded: true,
items: json,
chartData: {
labels: symbolsdate,
datasets: [{...this.state.chartData.datasets, data: closingprice}]
}
});
更好的是将动态部分和静态部分分开。存储静态数据,比如 backgroundColor
外的状态&在HTML中静态提供的 render()
而,使用状态变量来获取动态数据。