react-native 中的倒数计时器 [英] Countdown timer in react-native

查看:67
本文介绍了react-native 中的倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 react-native 中加载屏幕时从 3 倒计时到 1.我像这样用 setTimeOut 尝试过它,但它没有用.我在这里做错了什么?我怎样才能做到这一点?加载屏幕后,我想以 1 秒的间隔显示 3 =-> 2 ==> 1.这是我的代码.

I want to countdown from 3 to 1 when a screen is loaded in react-native. I tried it with setTimeOut like this and it didn't work. What am I doing wrong here? How can I achieve this? When the screen is loaded, I want to show 3 =-> 2 ==> 1 with 1 second interval. Here is my code.

 constructor(props) {
        super(props);

        this.state = {
            timer: 3
        }
    }

    // componentDidMount 
    componentDidMount() {
        setTimeout(() => {
            this.setState({
                timer: --this.state.timer
            })
        }, 1000);
    }

推荐答案

在你的代码中 setTimeout 在 componentDidMount 中被调用,ComponetDidMount 将在整个一次被调用>组件生命周期.因此, setTimeout 中的函数只会被调用一次.即在第一次渲染之后但在连续渲染之后,将不会调用 componentDidMount.

In your code setTimeout is called in componentDidMount and ComponetDidMount will be called once in whole component lifeCycle. So, the function within setTimeout will be called once only. i.e. just after the first render but upon successive render, the componentDidMount won't be called.

您的问题的解决方案可以是:

Solution to your problem can be:

constructor(props: Object) {
  super(props);
  this.state ={ timer: 3}
}

componentDidMount(){
  this.interval = setInterval(
    () => this.setState((prevState)=> ({ timer: prevState.timer - 1 })),
    1000
  );
}

componentDidUpdate(){
  if(this.state.timer === 1){ 
    clearInterval(this.interval);
  }
}

componentWillUnmount(){
 clearInterval(this.interval);
}

render() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', }}>
      <Text> {this.state.timer} </Text>
    </View> 
  )
}

'setInterval' 与 'setTimeout'

使用setState 中的函数而不是对象

Advantage of using a function in setState instead of an object

由于 setInterval 导致内存泄漏:如果我们在调用 clearInterval 之前卸载组件,则会出现内存泄漏,因为我们启动时设置的间隔和计时器没有停止.React 提供了 componentWillUnmount 生命周期方法作为清除组件卸载或移除时需要清除的任何内容的机会.

memory leak because of setInterval: if we unmount the component before clearInterval called, there is a memory leak because the interval that is set when we start and the timer is not stopped. React provides the componentWillUnmount lifecycle method as an opportunity to clear anything that needs to be cleared when the component is unmounted or removed.

我创建了一个名为 useCountDownTimer 的自定义挂钩,以在功能组件中使用此功能.如果有兴趣请查看此 GitHub 要点链接

I have created a custom hook called useCountDownTimer to use this functionality in a functional component. If interested please check this GitHub gist link

这篇关于react-native 中的倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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