[英]reactjs setInterval doesn't work as expected
I'm new to reactJS. 我是新来的反应犹太人。
I'm trying to attached time on my web page. 我想把时间花在我的网页上。 But, when I use
setInterval
the time doesn't work. 但是,当我使用
setInterval
,时间不起作用。 Just stops at the current time when the page loaded. 只是在页面加载时停止。
I'm using React.createClass: 我正在使用React.createClass:
var MainContent = React.createClass({
getInitialState: function(){
return {waktu: new Date().toLocaleTimeString()}
},
componentDidMount: function(){
setInterval(this.tick, 1000)
},
tick: function(){
this.setState({waktu: this.state.waktu})
},
render: function(){
return(
<div className="container">
<div className="panel panel-success">
<div className="panel-heading">
<h3 className="panel-title">Panel title</h3>
</div>
<div className="panel-body">
Panel content
{this.state.waktu}
</div>
</div>
</div>
);
}
});
You need to bind this to your setTimeOut function you could see more about it here : https://facebook.github.io/react/docs/handling-events.html 你需要将它绑定到你的setTimeOut函数,你可以在这里看到更多关于它的信息: https : //facebook.github.io/react/docs/handling-events.html
setInterval(this.tick, 1000).bind(this)
and for change your date just apply a new date to your state: 并且为了更改您的日期,只需在您的州申请新的日期:
this.setState({waktu: new Date()})
Pull your initial time code into a separate function and call that whenever you setState
. 将初始时间代码拉入单独的函数,并在设置
setState
时调用它。
function getTime() {
return new Date().toLocaleTimeString()
}
getInitialState: function() {
return { waktu: getTime() }
}
tick: function() {
this.setState({ waktu: getTime() })
}
You do also need to bind the function in your setInterval. 您还需要在setInterval中绑定该函数。
Setting the state to its own value after each interval wont help. 在每个间隔后将状态设置为自己的值不会有帮助。 You need to set to a current time
您需要设置为当前时间
var MainContent = React.createClass({ getInitialState: function(){ return {waktu: new Date().toLocaleTimeString()} }, componentDidMount: function(){ setInterval(this.tick, 1000) }, currentTime: function () { return new Date().toLocaleTimeString(); }, tick: function(){ this.setState({waktu: this.currentTime()}) }, render: function(){ return( <div className="container"> <div className="panel panel-success"> <div className="panel-heading"> <h3 className="panel-title">Panel title</h3> </div> <div className="panel-body"> Panel content {this.state.waktu} </div> </div> </div> ); } }); ReactDOM.render(<MainContent/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.