所以尝试进行api调用,然后根据json的输出设置状态,但是我创建了对象,但无法将该对象设置为状态。我在不同的react组件中做了类似的事情,并且效果很好。
TypeError:数据未定义
import { Bar, Line, Pie, Scatter } from "react-chartjs-2";
class Chart extends Component {
constructor(props) {
super(props);
this.state = {
test: {}
};
}
getPredictionData = company => {
fetch("http://127.0.0.1:5000/get_predict_price/" + company)
.then(res => res.json())
.then(json => {
var values = [];
for (let i = 0; i < json.length; i++) {
values = values.concat({ x: json[i][0], y: json[i][1] });
}
console.log(values);
var predictData = {
datasets: [
{
label: "Stock Prices",
data: values,
showLine: true,
pointRadius: 0,
borderColor: "blue",
backgroundColor: "rgba(0,0,0,0.1)"
}
]
};
console.log(predictData);
this.setState({
test: predictData
});
});
};
componentDidMount() {
this.getPredictionData(this.props.title);
}
render() {
return (
<div className="chart">
{" "}
<Scatter
data={this.props.chartData}
....
控制台输出:
Array(5)[{…},{…},{…},{…},{…}] 对象{数据集:(1)[…]}