我有下面的代码,当我运行该应用程序时,出现错误“ TypeError:无法读取未定义的属性'state'”
对于行“ y:this.state.mounts10”。
render(){
return(
<Line
data={{
datasets: [
{
label: "Dataset 1",
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 99, 132, 0.5)",
lineTension: 0,
borderDash: [8, 4],
data:this.state.mounts27
},
{
label: "Dataset 2",
borderColor: "rgb(255, 54, 132)",
backgroundColor: "rgba(255, 29, 132, 0.5)",
lineTension: 0,
borderDash: [8, 4],
data:this.state.mounts10
}
]
}}
options={{
scales: {
xAxes: [
{
type: "realtime",
realtime: {
onRefresh: function(chart) {
chart.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: this.state.mounts10
}.bind(this));
});
},
delay: 2000
}
}
]
}
}}
/>
)
}
有谁能很快帮助我吗?
chart.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: this.state.mounts10
}.bind(this));
});
this
中的[this.state.mounts10
]在这里指的是forEach匿名函数。最麻烦的修复将是这样的:
let that = this;
chart.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: that.state.mounts10
}.bind(this));
});
或者,如果您可以使用ES6,则可以使用继承父函数范围的箭头函数。如下所示:
chart.data.datasets.forEach(dataset => {
dataset.data.push({
x: Date.now(),
y: that.state.mounts10
}.bind(this));
});