Countdown timer in react-native

前端 未结 1 1189
难免孤独
难免孤独 2021-02-13 15:26

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

相关标签:
1条回答
  • 2021-02-13 16:20

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

    Advantage of using a function in setState instead of an object

    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.

    0 讨论(0)
提交回复
热议问题