React Native中的计时器(this.setTimeout) [英] Timers in React Native (this.setTimeout)

查看:837
本文介绍了React Native中的计时器(this.setTimeout)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的组件中设置TimeOut功能。
据我所知,只是像使用网络一样使用setTimeout不是一个正确的答案。它会导致计时和泄漏内存问题。

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.

我读过现有的 Timers API

然而,它不符合ES6,我引述:

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


请记住,如果您为React组件使用ES6类,则没有内置的mixin API。要将TimerMixin与ES6类一起使用,我们建议使用react-mixin。

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.

并在 react-mixin ,我们发现此消息:

And on react-mixin, we find this message :


注意: mixins基本上死了。仅将其用作旧代码的迁移路径。喜欢高阶组件。

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

所以我的最后一个问题是:我们如何正确使用计时器(setTimeOut),反应 - 本机,2017年?

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

推荐答案

Settimeout和setInterval仍然在react-native中工作。但是你必须以正确的方式使用它:

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

以下是在我通常使用的React中实现超时的许多方法之一:

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.

有一篇很好的文章谈论这个;你可以在这里参考: https:// medium。 com / @machadogj / timers-in-react-with-redux-apps-9a5a722162e8

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

这篇关于React Native中的计时器(this.setTimeout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆