ReactJS: setTimeout() not working?

前端 未结 10 2195

Having this code in mind:

var Component = React.createClass({

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

    componentDid         


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 07:54

    Your code scope (this) will be your window object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000) will crash this way.

    That comes from javascript not React, it is js closure


    So, in order to bind your current react component scope, do this:

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

    Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:

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

提交回复
热议问题