ReactJS:setTimeout()不起作用?

jbarradas:

请记住以下代码:

var Component = React.createClass({

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

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

    render: function () {
         return (
            <div className="component">
                {this.state.position}
            </div>
         ); 
    }

});

ReactDOM.render(
    <Component />,
    document.getElementById('main')
);

难道不应该在3秒后改变状态吗?它立即改变。

我这里的主要目标是每3秒更改一次状态(使用setInterval()),但是由于它不起作用,因此我尝试了setTimeout(),它也不起作用。上面有灯吗?谢谢!

丹尼尔·怀特:

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

否则,您会将的结果传递setStatesetTimeout

您还可以使用箭头功能来避免使用'this'关键字:

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

否则,您会将的结果传递setStatesetTimeout

您还可以使用ES6箭头功能来避免使用this关键字:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章