小编典典

ReactJS:setTimeout()不起作用?

reactjs

请记住以下代码:

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(),它也不起作用。上面有灯吗?谢谢!


阅读 425

收藏
2020-07-22

共1个答案

小编典典

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
);
2020-07-22