reactjs - Chartjs 没有呈现条形图,即使在控制台记录时图表变量正确显示
问题描述
我在使用 Reactjs 使用 Chartjs 渲染条形图时遇到问题。当我 console.logged 在 componentDidMount 中创建的图表变量时,它显示了正确的标签和数据(标签:(5)[“非常积极”,“有点积极”,“中性”,“有点消极”,“非常消极”]和数据:(5) [10, 17, 35, 34, 4])。但是,当我加载页面时,条形图不显示任何数据。我没有正确渲染条形图吗?
class BarChart extends Component {
constructor(props){
super(props);
this.state = {
render: false,
data : {
labels: [],
datasets: [
{
label: "Number of Tweets by Sentiment Category",
backgroundColor: "blue",
data: []
},
]
}
}
}
componentWillMount() {
this.getGraphs();
}
componentDidMount() {
console.log(this.state.data)
let el = ReactDOM.findDOMNode(this.refs.chart);
let ctx = el.getContext("2d");
let chart = new Chart(ctx, {
type: 'bar',
data: this.state.data,
options: {
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0
}
}]
}
}
}
);
console.log(chart)
this.setState({ render: true })
}
getGraphs = async() => {
let ticker = this.state.crypto;
let name = this.state.name;
let URL = 'http://localhost:5000/api/getGraphs';
let response = fetch(URL, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'name': name,
'ticker': ticker,
}
})
.then((response) => response.json())
.then((info) => {
let data = this.state.data;
data['labels'] = info.categories;
data['datasets']['data'] = info.count;
this.setState({ 'data': data })
})
}
render() {
return (
<div className='card'>
{ this.state.render = true &&
<canvas ref="chart" height="400px" />
}
</div>);
}
}
export default BarChart;
解决方案
这条线似乎是不正确的。您在这里分配一个值,而不是检查它是否为真。
{ this.state.render = true &&
<canvas ref="chart" height="400px" />
}
将其更改为:
{ this.state.render &&
<canvas ref="chart" height="400px" />
}
这可能不是根本原因,但只是想指出它。
推荐阅读
- angular - 强制刷新角度以进行打印
- arrays - 如何获取对数组中对象的引用
- angular - mat-form-field 必须包含一个 MatFormFieldControl。在 getMatFormFieldMissingControlError
- java - JavaFX - 将来自两个来源的数据库信息添加到 TableView (MVC) 中的更好方法
- html - 如何使元素表现得像表格对齐
- reactjs - ReatcJS:在 IE11 中使用 VX 库?
- google-tag-manager - 如何防止所有标签在某些页面上触发?
- reporting-services - SSRS 仅在参数的特定值中使用文本字段
- angular - Angular 6 - 两个路由器插座
- node.js - if/else 块中的车把相等性检查