记住这段代码:
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 许可协议
做
否则,您
setState
的结果传递给setTimeout
。您还可以使用 ES6 箭头函数来避免使用
this
关键字: