【发布时间】:2020-02-12 20:47:03
【问题描述】:
在通过从 API 获取的数据更新状态后,我在渲染图表时遇到了问题。
import React, { Component } from 'react';
import { Bar, Line, Pie } from 'react-chartjs-2';
export default class PopChart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: {
labels: [],
datasets: [
{
label: 'AAA',
data: [],
backgroundColor: []
}
]
}
};
}
url = 'api_url';
componentDidMount() {
fetch(this.url)
.then(response => {
this.setState({
httpStatusCode: response.status,
httpStatusOk: response.ok
});
if (response.ok) {
return response.json();
} else if (response.status === 404) {
// Not found
throw Error('HTTP 404, Not found');
} else {
throw Error(`HTTP ${response.status}, ${response.statusText}`);
}
})
.then(responseData => {
console.log('Then function');
this.setChartProperties(responseData);
})
.then(() => {
this.setState({ loading: false });
})
.catch(error => {
console.log(error);
});
}
setChartProperties = data => {
this.setChartData(data);
// this.setChartXAxis(data);
};
setChartData = data => {
let hours = data.map(event => event.hour);
hours = hours.splice(0, 10);
const { chartData } = { ...this.state };
const chartDataUpdate = chartData;
chartDataUpdate['datasets'].data = hours;
// Working version
// this.setState({
// chartData: {
// labels: ['a', 'a', 'a', 'a', 'a', 'a', 'a'],
// datasets: [
// {
// label: 'AAA',
// data: hours,
// backgroundColor: []
// }
// ]
// }
// });
// Not working version
this.setState({ chartData: chartDataUpdate });
};
render() {
<Bar data={this.state.chartData} />;
}
}
起初我认为问题在于 fetch() 的异步性质,并且 Chart.js 中的 <Bar/> 组件在状态有机会更新之前被渲染。但是,当我注销状态时,它会在控制台上显示我的状态以及更改后的值。但是,图表没有显示任何值。
当我调用setState() 并传递一个匿名对象(参考setState() 的注释掉的工作版本)时,图表显示了值。
当我将获取的数据存储到变量中并将其作为setState() 的参数传递时,为什么它不起作用?
【问题讨论】:
标签: reactjs chart.js fetch setstate