反应原生的倒数计时器

问题描述 投票:5回答:1

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

 constructor(props) {
        super(props);

        this.state = {
            timer: 3
        }
    }

    // componentDidMount 
    componentDidMount() {
        setTimeout(() => {
            this.setState({
                timer: --this.state.timer
            })
        }, 1000);
    }
react-native
1个回答
14
投票

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

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

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' vs 'setTimeout'

Advantage of using a function in setState instead of an object

memory leak because of setInterval:如果我们在调用clearInterval之前卸载组件,则会发生内存泄漏,因为我们启动时设置的时间间隔没有停止。 React提供componentWillUnmount生命周期方法,以便在卸载或删除组件时清除需要清除的任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.