每x秒更新一次状态

jt1*_*123 12 react-native

我试图每3秒更新一次状态.

export default class Calendar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      timeLineTop: 75,
    };
  }

render() {
    this.state.timeLineTop = setInterval(function () {
      let d = new Date();
      let result = d.getHours() + d.getMinutes() / MINUTES_IN_HOUR;

      return result;
    }, 3000);

    <View style={[
          { top: this.state.timeLineTop },
        ]}></View>
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么这不会每3秒更新一次我的观点位置?

Nad*_*bit 15

**更新以实现TimerMixin

您需要调用this.setState来更新状态变量,并且由@ eyal83指定,将TimerMixin用于setTimeout和setInterval:

var TimerMixin = require('react-timer-mixin');

componentDidMount: function() {
  this.setInterval( () => { 
       let d = new Date();
       let result = d.getHours() + d.getMinutes() / MINUTES_IN_HOUR;
       this.setState({
           timeLineTop: result
       })
    }, 500);
}
Run Code Online (Sandbox Code Playgroud)

我还建立了一个基本的应用程序重置与setInterval的状态变量这里,代码如下.https://rnplay.org/apps/9gD-Nw

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var TimerMixin = require('react-timer-mixin');

var SampleApp = React.createClass({
  mixins: [TimerMixin],
  getInitialState: function() {
        return {
            timeLineTop: 75
        }
    },

  componentDidMount: function() {
    this.setInterval( () => { 
      this.setState({
        timeLineTop: this.state.timeLineTop+1
      })
    }, 500);
  },

  render: function() {

    return (
      <View style={styles.container}>
       <View style={[
          { marginTop: this.state.timeLineTop },
        ]}><Text>TOP - {this.state.timeLineTop}</Text></View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:60,
  },
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);
Run Code Online (Sandbox Code Playgroud)


eya*_*l83 10

全局使用setTimeout和setInterval是一个非常糟糕的主意.

我们强烈建议不要使用全局setTimeout(...),而是建议您使用react-timer-mixin提供的this.setTimeout(...).这将消除许多追踪错误的艰苦工作,例如卸载组件后因超时触发而导致的崩溃.

更多信息:https://facebook.github.io/react-native/docs/timers.html#timermixin

包括这样的计时器mixin:

var TimerMixin = require('react-timer-mixin');

var Component = React.createClass({
  mixins: [TimerMixin],
  componentDidMount: function() {
    this.setInterval(
      () => { console.log('I do not leak!'); },
      500
    );
  }
});
Run Code Online (Sandbox Code Playgroud)


Tia*_*des 7

此代码适用于React Native 0.47.1

import TimerMixin from 'react-timer-mixin';

mixins: [TimerMixin];

export class MyClass extends Component {

    componentDidMount() {

        this.interval = setInterval(() => {
            console.log("Hi");

        }, 6000); //6 seconds

    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }
}
Run Code Online (Sandbox Code Playgroud)