Accessing this in a forEach loop results in undefined

后端 未结 3 954
不思量自难忘°
不思量自难忘° 2020-11-30 06:21

I\'m iterating through an array using forEach in one of my Class\'s methods. I need access to the instance of the class inside the forEach but this is undef

3条回答
  •  时光说笑
    2020-11-30 06:24

    What I had to to is add this in the every forEach that I was using (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach ). Binding in the constructor is not needed, as I am using arrow functions. So now my code is:

    resetPressed = () => {
        this.transport_options.forEach(function (transport_option) {
            this.pressed_percentages.forEach(function (percentage) {
                filters[transport_option][percentage] = false;
            }, this)
        }, this);
    
        filters.isFilterActive = false;
        this.setState({
            filtersState: filters,
            opacity: filters.isFilterActive ? 1 : 0.5
        });
    
    }
    
    
    
    

提交回复
热议问题