React Native Timer not triggering

时间:2016-07-11 22:01:57

标签: javascript reactjs react-native

I'm trying to make a simple countdown in React Native. I used the TimerMixin, however nothing is updating.

I'm not sure why the Timer is not running the timeout.

import React from 'react-native'
var TimerMixin = require('react-timer-mixin');
var reactMixin = require('react-mixin');

const {
    Dimensions,
    StyleSheet,
    ScrollView,
    View,
    Image,
    Text,
    Component,
} = React;

class Countdown extends Component {
    constructor() {
      super();
      this.state = {
        targetDate: "09/09/2016",
        time: {
          total: 0, 
          days: 0,
          hours: 0, 
          minutes: 0,
          seconds: 0
        }
      }
      
    }
  
    componentDidMount() {
      this.timer = TimerMixin.setTimeout(() => { 
          console.log('Refreshing ' + this.state.time.seconds);
          this.refresh();
        },100);
    }
  
    componentWillUnmount() {
      TimerMixin.clearTimeout(this.timer);
    }

    refresh() {
      var t = Date.parse(this.state.targetDate) - Date.parse(new Date());
      var seconds = Math.floor( (t/1000) % 60 );
      var minutes = Math.floor( (t/1000/60) % 60 );
      var hours = Math.floor( (t/(1000*60*60)) % 24 );
      var days = Math.floor( t/(1000*60*60*24) );
      var time = {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
      };
      
      this.setState({targetDate: this.state.targetDate, time: time});    
    }
  
    render() {
      // Render omitted for simplicity of question
     }
}

reactMixin(Countdown.prototype, TimerMixin);

module.exports = Countdown;

I only get "Refreshing 0", once on initialization.

1 个答案:

答案 0 :(得分:0)

Solved. The problem was I had setTimeout, instead of setInterval. Obviously this would cause the timer to only run once after 100ms and only then.