2017-12-10 18 views
0

setState을 setTimeout 안에 어떻게 사용할 수 있습니까? 나는 생성자 함수 안에 속성을 선언했다. 나는 내가 많은 문제를 해결하는 방법을 몰라 시도 Uncaught TypeError: this.setState is not a functionsetState는 내부에서 사용하는 동안 함수가 아닙니다. Reactjs

constructor(props) { 
    super(props); 
    this.state = { 
     count: 0 
    }; 
    this.onMouseDown = this.onMouseDown.bind(this); 
    } 
onMouseDown() { 
    this.timer(); 
    } 
timer() { 
    for (var i = 1; i <= 90; i++) { 
     (function(index) { 
     setTimeout(function() { 
      this.setState({ count: index }); 
     }, index * 10); 
     })(i); 
    } 
    } 

과 같은 오류가 발생합니다 setTimeout 내부 this.setState({ count: index });을 사용했다. 그리고 왜 그것이 틀린거야?.이 문제에서 나를 꺼내십시오 ..

+1

또한 관련 : https://stackoverflow.com/questions/42650102/react-this-setstate-is-not-a-function-inside-settimeout – ivarni

답변

0

this이이 자료를 참조하지 않습니다. setState이 구성 요소에 정의 this

timer() { 
    const objThis = this; //store this. 
     for (var i = 1; i <= 90; i++) { 
      (function(index) { 
      setTimeout(function() { 
       objThis.setState({ count: index }); 
      }, index * 10); 
      })(i); 
     } 
     }