Calling function at set intervals in React presentational component [duplicate]

谁都会走 提交于 2020-01-17 14:45:13

问题


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;


来源:https://stackoverflow.com/questions/48056256/calling-function-at-set-intervals-in-react-presentational-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!