简体   繁体   中英

how do count down every time on same view with react native expo

I am new to react and react native. I am using the expo cli to build a react native app. How do I restart a countdown every time view is viewed by a user? unmount doesn't work since this never unmount. What I want is to count down to 15 to 0 and then show the continue button but this only works once.

function ContinueStatus({ onContinuePress }) {
      let [count, setTimer] = useState(15);
  let [isStarted, setIsStarted] = useState(true);

  useEffect(() => {
    let interval = setInterval(() => {
      setTimer(lastTimerCount => {
          lastTimerCount <= 1 && clearInterval(interval);
          count = lastTimerCount;
          return lastTimerCount - 1
      })
    }, 1000) 
    //cleanup the interval on complete
    return () => clearInterval(interval)
  }, [isStarted]);

    return( 
      count > 0 ?
        (<Button color="primary" style={styles.createButton}>
        <Text bold size={14} color={myTheme.COLORS.WHITE}>
          Continue in {count} second(s)
        </Text>
        </Button> )
      :
       (<Button color="primary" style={styles.createButton} onPress={onContinuePress} >
            <Text bold size={14} color={myTheme.COLORS.WHITE}>
              Continue
            </Text>
          </Button> 
       )
  ) 
}
render() { 
    return (
          <ContinueStatus onContinuePress={this.onContinuePress}/> 
  );
}

The problem is is that your component doesn't unmount when you navigate away from it. This is one significant difference between ReactJS and React Native. The problem can be solved by using React Navigation and the useFocusEffect hook.

The useFocusEffect is analogous to React's useEffect hook. The only difference is that it only runs if the screen is currently focused.

So replace useEffect with useFocusEffect and make sure to use useCallback like it describes in the docs .

You may also need to set up the router with a provider, but try it without first.

I found a way to do it from this article.

https://aboutreact.com/refresh-previous-screen-react-navigation/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM