反应:如何在AddListener()中使用setState? [英] React: How to use setState in AddListener()?

查看:176
本文介绍了反应:如何在AddListener()中使用setState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,可以在您单击按钮之前,对尚不存在的数据调用addListener.但是,当我尝试在状态中设置该数据时,出现以下错误:

I have a method that calls an addListener to data that does not exist yet until you've clicked on a button. However, as I try to set that data inside a state, I get the following error:

TypeError:this.setState不是函数

TypeError: this.setState is not a function

我试图像这样绑定我的dataHandler:

I've tried binding my dataHandler like this:

this.dataHandler = this.dataHandler.bind(this)

但是它仍然返回此错误.我在这里忘记了什么?

yet it still returns this error. What am I forgetting here?

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})
    });
}

推荐答案

在JavaScript中,this始终是指我们正在执行的函数的所有者",或更确切地说,是指对象是该函数的方法的对象. . 请改用箭头功能. 箭头函数没有自己的this/super/arguments绑定.它从其父词法范围继承它们.

In JavaScript this always refers to the "owner" of the function we're executing, or rather, to the object that a function is a method of. Use arrow function instead. An arrow functions doesn't have its own this/super/arguments binding. It inherits them from its parent lexical scope.

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})
});

参考:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

这篇关于反应:如何在AddListener()中使用setState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆