我调用了 update()
函数,但它不起作用。
TypeError: line.update is not a function.
为什么 update()
不是函数?
我在 http://jsfiddle.net/zpnx8ppb/26/ 上看过这个例子更新功能起作用的地方
这是我的代码:
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
const line = {
labels: [],
datasets: [
{
label: 'My First dataset',
fill: false,
data: []
}
]
};
setInterval(function(){
line.labels.push(Math.floor(Math.random() * 100));
line.datasets[0].data.push(Math.floor(Math.random() * 100));
line.update();
}, 5000);
class LineChart extends Component {
render() {
return (
<div className="chart">
<Line
data={this.state}
height={5}
width={20}
/>
</div>
)
}
}
export default LineChart;
最佳答案
所以根据https://www.npmjs.com/package/react-chartjs-2
可以使用诸如
之类的引用来访问图表引用chartReference = {};
componentDidMount() {
console.log(this.chartReference); // returns a Chart.js instance reference
}
render() {
return (<Doughnut ref={(reference) => this.chartReference = reference } data={data} />)
}
所以您可以做的是在您的图表中放置一个引用,并在您喜欢的任何地方访问它。
<Line
data={this.state}
height={5}
width={20}
ref = {(reference) => this.reference = reference}
/>
在您希望导致更新的方法中,您可以访问此引用及其 chartInstance 并调用此实例的更新函数。
let lineChart = this.reference.chartInstance
lineChart.update();
关于javascript - 如何在 react-chartjs-2 中更新图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053257/