【发布时间】:2019-06-16 18:20:50
【问题描述】:
我有一个方法可以调用 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})
});
}
【问题讨论】:
-
你能用
()=>箭头函数代替function(event) -
谢谢! @HaiPham 也建议这样做。
-
@CédricBloem 抱歉缺少解释,我已经更新了我的答案
-
@Hai Pham 没问题!我立即注意到并阅读了文档 :) 感谢您提供的信息!
标签: reactjs listener bind typeerror setstate