简体   繁体   中英

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. Just stops at the current time when the page loaded.

I'm using 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 &nbsp;
            {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

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 .

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.

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 &nbsp; {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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM