Presentation组件中按设置的间隔调用函数

Presentation组件中按设置的间隔调用函数

本文介绍了在React Presentation组件中按设置的间隔调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的国家/地区React组件中的moment.js来实现滴答计时器.第一步,我想每秒调用一次函数,但不是得到函数应返回的文本,而是得到一个int值.

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?

这是我的组成部分:

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;

React呈现页面时,我没有看到00:02:48的值,而是上升了3倍的int值. 20、21、22

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?

推荐答案

其原因是setInterval返回了timerId,您可以稍后使用它清除间隔.

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;

这篇关于在React Presentation组件中按设置的间隔调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:34