ReactJS: setTimeout() not working?

前端 未结 10 2184

Having this code in mind:

var Component = React.createClass({

    getInitialState: function () {
        return {position: 0};    
    },

    componentDid         


        
10条回答
  •  伪装坚强ぢ
    2020-12-04 08:00

    There's a 3 ways to access the scope inside of the 'setTimeout' function

    First,

    const self = this
    setTimeout(function() {
      self.setState({position:1})
    }, 3000)
    

    Second is to use ES6 arrow function, cause arrow function didn't have itself scope(this)

    setTimeout(()=> {
       this.setState({position:1})
    }, 3000)
    

    Third one is to bind the scope inside of the function

    setTimeout(function(){
       this.setState({position:1})
    }.bind(this), 3000)
    

提交回复
热议问题