Uncaught TypeError: this.setState is not a function

0

Why can this error be caused in my code?

componentDidMount(){

let container = document.getElementById('body');

container.onscroll = function () {
  let height = this.clientHeight;
  let scrollHeight = this.scrollHeight;
  let scrollTop = this.scrollTop;
  
  if (height + scrollTop === scrollHeight) {
     this.setState({ display: 'loader'});
    }
  }
}
    
asked by Santiago D'Antuoni 24.02.2017 в 20:18
source

1 answer

1

Considering that container is an HTMLElement, there is no where to have a setState method so I imagine that the idea of your code is to invoke that method on componentDidMount or rather, on the class that contains it.

You can test by declaring a reference to this outside the context of the function onscroll .

componentDidMount(){
    let _this=this;
    let container = document.getElementById('body');

    container.onscroll = function () {
      let height = this.clientHeight;
      let scrollHeight = this.scrollHeight;
      let scrollTop = this.scrollTop;

      if (height + scrollTop === scrollHeight) {
         _this.setState({ display: 'loader'});
        }
    }
}
    
answered by 24.02.2017 / 20:38
source