ReactJS: setTimeout() not working?

前端 未结 10 2190

Having this code in mind:

var Component = React.createClass({

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

    componentDid         


        
10条回答
  •  情话喂你
    2020-12-04 07:54

    You didn't tell who called setTimeout

    Here how you call timeout without calling additional functions.

    1. You can do this without making additional functions.

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

    Uses function.prototype.bind()

    setTimeout takes the location of the function and keeps it in the context.

    2. Another way to do the same even by writing even less code.

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

    Probably uses the same bind method at some point

    The setTimeout only takes the location of the function and the function already has the context? Anyway, it works!

    NOTE: These work with any function you use in js.

提交回复
热议问题