代码
import * as React from 'react';
import {View, StyleSheet, Text} from 'react-native';
export default function CountScreen() {
const [count, setCount] = React.useState(100);
const latestCount = React.useRef(count);
React.useEffect(() => {
latestCount.current = count;
});
React.useEffect(() => {
const timer = setInterval(() => {
if (latestCount.current === 0) {
clearInterval(timer);
return;
}
setCount(c => c - 1);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return (
<View style={styles.container}>
<Text style={styles.text}>倒计时{count}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 30,
},
});
参考
https://juejin.cn/post/6932425746493210632