我有一个方法,它对数据调用addListener,直到单击按钮后才存在。但是,当我试图在状态内设置数据时,我会得到以下错误:
TypeError: this.setState不是一个函数
我尝试过像这样绑定我的dataHandler:
this.dataHandler = this.dataHandler.bind(this)然而,它仍然返回此错误。我忘了什么?
constructor(props){
super(props)
this.state = {
selActive: 4,
loaded: false,
mapInfo: ''
}
this.onScriptLoad = this.onScriptLoad.bind(this)
this.dataHandler = this.dataHandler.bind(this)
}
dataHandler = (getJson) => {
fetch(getJson)
.then(response => response.json())
.then(featureCollection =>
dataLayer = map.data.addGeoJson(featureCollection)
);
map.data.addListener('mouseover', function(event) {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {fillColor: 'blue'});
// THIS IS WHERE I ADD MY SETSTATE.
// HOWEVER, THIS RETURNS AN ERROR ON HOVER
this.setState({mapInfo: event.feature.countryNL})
});
}发布于 2019-01-23 08:05:16
在JavaScript中,this总是指我们正在执行的函数的“所有者”,或者更确切地说,指函数的方法所在的对象。使用箭头函数代替。箭头函数没有自己的this/super/arguments绑定。它从其父词法范围继承它们。
map.data.addListener('mouseover', (event) => {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {fillColor: 'blue'});
// THIS IS WHERE I ADD MY SETSTATE.
// HOWEVER, THIS RETURNS AN ERROR ON HOVER
this.setState({mapInfo: event.feature.countryNL})
});参考资料:
发布于 2019-01-23 08:15:43
普通函数中的this要么是指全局对象,要么是当前实例(如果是通过new调用的话)。但是,箭头函数中的this是从外部作用域中捕获的。因此,this内部的addListener回调指的是全局对象(window)。要解决这个问题,您有以下选项:
发布于 2019-01-23 08:22:22
首先,我不建议您使用匿名函数将其设置为事件侦听器,因为在本例中,您将无法使用removeEventListener或什么simillar (可能是因为不清楚这里的map是什么)。
第二件事是,您不应该绑定您的dataHandler,因为它已经是一个箭头函数,所以this在dataHandler上下文中没有问题。您应该绑定的是手动事件列表程序。因此,结果代码应该如下所示:
constructor(props){
super(props)
this.state = {
selActive: 4,
loaded: false,
mapInfo: ''
}
this.onScriptLoad = this.onScriptLoad.bind(this)
this.dataHandler = this.dataHandler.bind(this)
this.handleMouseOver = this.handleMouseOver.bind(this)
}
dataHandler = (getJson) => {
fetch(getJson)
.then(response => response.json())
.then(featureCollection =>
dataLayer = map.data.addGeoJson(featureCollection)
);
map.data.addListener('mouseover', this.handleMouseOver);
}
handleMouseOver(event) {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {fillColor: 'blue'});
this.setState({mapInfo: event.feature.countryNL})
}或者,使用箭头函数自动绑定:
constructor(props){
super(props)
this.state = {
selActive: 4,
loaded: false,
mapInfo: ''
}
this.onScriptLoad = this.onScriptLoad.bind(this)
this.dataHandler = this.dataHandler.bind(this)
}
dataHandler = (getJson) => {
fetch(getJson)
.then(response => response.json())
.then(featureCollection =>
dataLayer = map.data.addGeoJson(featureCollection)
);
map.data.addListener('mouseover', this.handleMouseOver);
}
handleMouseOver = (event) => {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {fillColor: 'blue'});
this.setState({mapInfo: event.feature.countryNL})
}希望,这将对你有帮助!)
https://stackoverflow.com/questions/54322518
复制相似问题