Calling function at set intervals in React present

2019-09-20 12:03发布

问题:

This question already has an answer here:

  • javascript setTimeout() not working [closed] 7 answers
  • setInterval/setTimeout return value 6 answers

I'm trying to implement a ticking timer using moment.js in my presenational React component. As a first step, I wanted to just call a function every second but instead of getting the text the function should return, I'm getting an int value.

Any idea how I should implement this?

Here's my component:

import React, { PropTypes } from 'react';
import moment from 'moment';

const tickingTimer = () => {

   return "00:02:48";
}

const MyComponent = () => {

   return(
      <div>
         <div>{setInterval(tickingTimer(), 1000)}</div>
      </div>
   );
}

export default MyComponent;

When React renders the page, instead of seeing 00:02:48, I'm getting int values that go up 3 times e.g. 20, 21, 22

How do call a function that will return a value every second in my presentational component?

回答1:

The reason for it is that setInterval returns a timerId which you can use later to clear the interval.

You need to save the returned value of function in state

import React, { PropTypes } from 'react';
import moment from 'moment';

const tickingTimer = () => {

   return "00:02:48";
}

const MyComponent class extends React.Component {
   state = { 
      timer: ''
   }
   componentDidMount(){
       setInterval(tickingTimer, 1000)
   }

   tickingTimer = () => {

     this.setState({timer:"00:02:48"});
    }
   return(
      <div>
         <div>{this.state.timer}</div>
      </div>
   );
}

export default MyComponent;