ReactJS:setTimeout() 不起作用?

新手上路,请多包涵

记住这段代码:

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

原文由 jbarradas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 930
1 个回答

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

否则,您 setState 的结果传递给 setTimeout

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

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

原文由 Daniel A. White 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题