javascript 使用 es6 创建带有本机反应的计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31963803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:39:58  来源:igfitidea点击:

create timer with react native using es6

javascriptiosfacebookreactjsreact-native

提问by ak85

I am looking to add a timer to my app which is built using react native.

我希望向我的应用程序添加一个计时器,该计时器是使用 React Native 构建的。

I have looked at the link to the timer mixinin the documentation however I have built the rest of the app using es6 so this won't be compatible.

我已经查看了文档中计时器 mixin的链接,但是我已经使用 es6 构建了应用程序的其余部分,因此这将不兼容。

I have tried the below.

我已经尝试了以下。

In my Main class I have a function called getTimerCountDown

在我的 Main 类中,我有一个名为 getTimerCountDown

getTimerCountDown() {
    setTimeout(() => {
      this.setTimeRemaining(this.getTimeRem()-1);
    }, 1000);
}

getTimeRem() {
    return this.state.timeRemaining;
}

I have tried calling this in componentDidUpdateas shown below. This works as I want it to if I don't make any other interactions with the UI.

我试过调用它,componentDidUpdate如下所示。如果我不与 UI 进行任何其他交互,这将按我的意愿工作。

If I do (eg I have a button I can click on the view.) as `componentDidUpdate gets called again the conunter gets really quick (as it is getting called x number of times)

如果我这样做(例如,我有一个按钮,我可以单击视图。)因为`componentDidUpdate 再次被调用,conunter 会变得非常快(因为它被调用了 x 次)

componentDidUpdate(){
    this.getTimerCountDown();
}

I am not sure if I am completly on the wrong track here or a small change to what I have done can get me what I want. What is the best way to get a countdown timer working in react native using es6?

我不确定我是否在这里完全走错了路,或者对我所做的做一个小小的改变就能让我得到我想要的。让倒数计时器在使用 es6 的本机反应中工作的最佳方法是什么?

Timer Class on main page

主页上的计时器类

<Timer timeRem={this.getTimeRem()} />

returns

回报

render(){
    return (
        <View style={styles.container}>
            <Text> This is the Timer : {this.props.setTimer}  - {this.props.timeRem} </Text>
        </View>
    )
}

采纳答案by tkers

I'm not really sure how that would work even without any other UI interactions. componentDidUpdateis called every time the component is re-rendered, something that happens when the internal state or passed down props have changed. Not something you can count on to happen exactly every second.

即使没有任何其他 UI 交互,我也不确定这将如何工作。componentDidUpdate每次重新渲染组件时都会调用,当内部状态或传递的 props 发生变化时会发生一些事情。不是你可以指望每一秒都发生的事情。

How about moving the getTimerCountDownto your componentDidMountmethod (which is only called once), and then using setIntervalinstead of setTimeoutto make sure the counter is decremented continuously?

如何将 移动getTimerCountDown到您的componentDidMount方法(仅调用一次),然后使用setInterval而不是setTimeout确保计数器连续递减?

回答by kapv89

Kinda late, but you can try out this component I made for dealing with timers and es6 components in react-native:

有点晚了,但是你可以试试我为在 react-native 中处理计时器和 es6 组件而制作的这个组件:

https://github.com/fractaltech/react-native-timer

https://github.com/fractaltech/react-native-timer

Idea is simple, maintaining and clearing timer variables on the components is a pain, so simply, maintain them in a separate module. Example:

想法很简单,维护和清除组件上的定时器变量很痛苦,所以简单,将它们维护在一个单独的模块中。例子:

// not using ES6 modules as babel has broken interop with commonjs for defaults 
const timer = require('react-native-timer');

// timers maintained in the Map timer.timeouts 
timer.setTimeout(name, fn, interval);
timer.clearTimeout(name);

// timers maintained in the Map timer.intervals 
timer.setInterval(name, fn, interval);
timer.clearInterval(name);

// timers maintained in the Map timer.immediates 
timer.setImmediate(name, fn);
timer.clearImmediate(name);

// timers maintained in the Map timer.animationFrames 
timer.requestAnimationFrame(name, fn);
timer.cancelAnimationFrame(name);

回答by Akash sharma

Try this

试试这个

Timer.js

定时器.js

import React, { Component } from "react";
import { View,Text,Button,StyleSheet } from "react-native";
const timer = () => {};
class Timer extends Component {
    constructor(props) {
    super(props);
    this.state = {
      remainingTime: 10
     };
    }

 countdownTimer(){
   this.setState({remainingTime:10 });
   clearInterval(timer);
   timer = setInterval(() =>{
        if(!this.state.remainingTime){
          clearInterval(timer);
          return false;
        }
        this.setState(prevState =>{
        return {remainingTime: prevState.remainingTime - 1}});
        },1000);
    }

    render() {
      return (
       <View style={styles.container}>
         <Text>Remaining time :{this.state.remainingTime}</Text>
          <Button title ="Start timer" onPress={()=>this.countdownTimer()}/>
       </View>
     );
   }
  }


  const styles = StyleSheet.create({
    container:{
     flex:1,
     justifyContent:'center',
     alignItems:'center',
   } 
});

  export default Timer;

App.js

应用程序.js

import React, { Component } from "react";
  import { View,Text,Button,StyleSheet } from "react-native";
  import Timer from './timer';

  export default class App extends Component{
   render(
    return (<Timer />)
   );
 }