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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47513549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:25:51  来源:igfitidea点击:

Timers in React Native (this.setTimeout)

javascriptreact-nativetimer

提问by Louis Lecocq

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.

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

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

我读过在 react-native 中有一个现有的Timers API

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

但是,它不符合 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 组件使用 ES6 类,则没有用于 mixins 的内置 API。要将 TimerMixin 与 ES6 类一起使用,我们建议使用 react-mixin。

And on react-mixin, we find this message :

react-mixin 上,我们发现了这条消息:

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

注意:mixin 基本上已经死了。仅将此用作遗留代码的迁移路径。首选高阶组件。

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

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

回答by chiquyet

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

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

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

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

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

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

回答by DevAelius

Take refrencefrom @chiquyet , Thank you @chiquyet

就拿refrence从@chiquyet, 谢谢@chiquyet

https://stackoverflow.com/a/47549754/11754047

https://stackoverflow.com/a/47549754/11754047

this.clearInterval(this.state.timer);

Will throw error in react native

会在本机反应中引发错误

Description

描述

Simple timer in react native with 5 secounds, along with validationand alert

简单的计时器以 5 秒响应本机,以及验证警报

I try in, () => "react": "16.9.0", "react-native": "0.61.5",

我尝试, () => "react": "16.9.0", "react-native": "0.61.5",

Snack Expo Link () => https://snack.expo.io/PuYxRmueW

小吃展链接 () => https://snack.expo.io/PuYxRmue​​W

import React from 'react'
import { View, Text, Button, SafeAreaView, TextInput } from 'react-native'

export default class Timer extends React.Component {

    state = {
        timer: null,
        counter: 5,
    };

    startTimer = () => {

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

    }

    manageTimer = () => {

        var states = this.state

        if (states.counter === 0) {
            alert('Times Up !\nTimer  is reset')
            clearInterval(this.state.timer)
            this.setState({
                counter: 5
            })
        }
        else {
            this.setState({
                counter: this.state.counter - 1
            });

        }
    }

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



    render() {
        return (
            <SafeAreaView>


                <Text style={{ textAlign: 'center' }}>{this.state.counter}</Text>

                <View>
                    <Button
                        title='START TIMER'
                        onPress={() => this.startTimer()}
                    />
                </View>
            </SafeAreaView>
        )
    }
}

Hope this will help you :)

希望能帮到你 :)

回答by SKeney

For the sake of also adding what it would look like with functional component and hooks.

为了还添加功能组件和钩子的外观。

import React, { useEffect } from 'react'
import { Text } from 'react-native'

const Component = props => {

    useEffect(() => {
        let timer = setInterval(() => console.log('fire!'), 1000);

        return () => clearInterval(timer)
    }, [])

    return <Text>Example of using setInterval with hooks</Text>
}

回答by Alex V

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

计时器不是“react-native”包的一部分

  • 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);
    
  • cd /path_to_your_project
  • 安装 react-timer-mixin 包
  • 在 .js 文件中添加计时器
  • 设置定时器

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