javascript - React Native 中的定时器 (this.setTimeout)

标签 javascript react-native timer

我正在尝试在我的组件中设置一个 TimeOut 函数。 据我了解,仅仅像在网络上那样使用 setTimeout 并不是一个正确的答案。这会导致时序和内存泄漏问题。

我读到有一个现有的 Timers API在 native react 中。

但是,它不符合 ES6,我引用:

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 ,我们发现这条消息:

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

所以我的最后一个问题是:我们如何在 2017 年通过 react-native 正确使用计时器 (setTimeOut)?

最佳答案

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

这是我经常使用的在 React 中实现超时的众多方法之一:

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

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

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

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

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

使用这种方法,您不必再担心内存泄漏。简单直接。

有一篇很棒的文章谈到了这一点;你可以在这里引用:https://medium.com/@machadogj/timers-in-react-with-redux-apps-9a5a722162e8

关于javascript - React Native 中的定时器 (this.setTimeout),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513549/

相关文章:

javascript - react native -调试[对象对象]handleException-Observable

linux - HR 计时器精度研究案例

c - STM32VLDiscovery定时器中断HardFault c

react-native - 我如何在React Native中一次请求多个权限

javascript - 跨源请求仅支持 react 中的协议(protocol)方案错误

c# - 即使应用程序处于后台,Time.unscaledDeltaTime 仍然在计数

javascript - 密码的正则表达式,规则很少

javascript - Mongoose 5.x 不允许传递一系列运算符

Javascript:在谷歌地图中添加和删除折线?

javascript - 如何自动点击确认框?