React Native中的计时器(this.setTimeout)

时间:2017-11-27 14:41:13

标签: javascript react-native timer

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

我已经读过现有的Timers API反应原生。

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

  

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

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

  

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

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

3 个答案:

答案 0 :(得分:12)

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() {
    this.clearInterval(this.state.timer);
  }

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

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

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

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

答案 1 :(得分:4)

为了也添加功能组件和挂钩的外观。

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>
}

答案 2 :(得分:1)

从@chiquyet获取参考谢谢@chiquyet

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

this.clearInterval(this.state.timer);

反应原生

中会引发错误

说明

简单的计时器,可以响应5秒的声音,并带有验证警报

我尝试,()=> “反应”:“ 16.9.0”, “ react-native”:“ 0.61.5”,

零食博览会链接()=> https://snack.expo.io/PuYxRmueW

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>
        )
    }
}

希望这会对您有所帮助:)