Timers in React Native (this.setTimeout)

2019-04-24 18:45发布

问题:

I'm trying to set up a TimeOut function in my component. To my understanding, just using setTimeout as you would for the web isn't a proper answer. It would cause timing and leak memory issue.

I've read there is an existing Timers API in react-native.

However, it is not compliant with ES6, i quote :

Keep in mind that if you use ES6 classes for your React components there is no built-in API for mixins. To use TimerMixin with ES6 classes, we recommend react-mixin.

And on react-mixin, we find this message :

Note: mixins are basically dead. Only use this as a migration path for legacy code. Prefer High Order Components.

So my final question is : How do we properly use timers (setTimeOut), with react-native, in 2017 ?

回答1:

Settimeout and setInterval still work in react-native. BUT you have to use it in the right way:

Here is one of many ways to implement a timeout in React that I'm usually used:

export default class Loading extends Component {
  state = {
    timer: null,
    counter: 0
  };

  componentDidMount() {
    let timer = setInterval(this.tick, 1000);
    this.setState({timer});
  }

  componentWillUnmount() {
    this.clearInterval(this.state.timer);
  }

  tick =() => {
    this.setState({
      counter: this.state.counter + 1
    });
  }

  render() {
    <div>Loading{"...".substr(0, this.state.counter % 3 + 1)}</div>
  }
}

With this approach you don't have to worry about memory leak anymore. Just simple and straight forward.

There is an excellent article talking about this; you can refer to it here: https://medium.com/@machadogj/timers-in-react-with-redux-apps-9a5a722162e8



回答2:

Timer is not a part of 'react-native' package

  • cd /path_to_your_project
  • install react-timer-mixin package
  • add Timer in .js file
  • setup timer

    npm i react-timer-mixin --save (from console)
    
    import TimerMixin from 'react-timer-mixin';
    this.interval = setInterval(() => {
        //DO SOMETHING
    }, 5);