当以 react-native 加载屏幕时,我想从 3 倒计时到 1。我用这样的 setTimeOut 尝试过,但没有用。我在这里做错了什么?我怎样才能做到这一点?加载屏幕后,我想以 1 秒的间隔显示 3 =-> 2 ==> 1。这是我的代码。
constructor(props) {
super(props);
this.state = {
timer: 3
}
}
// componentDidMount
componentDidMount() {
setTimeout(() => {
this.setState({
timer: --this.state.timer
})
}, 1000);
}
最佳答案
更新 Hook (使用 useEffect )版本到 倒计时使用 设置间隔 在 native react 中:
const [timerCount, setTimer] = useState(60)
useEffect(() => {
let interval = setInterval(() => {
setTimer(lastTimerCount => {
lastTimerCount <= 1 && clearInterval(interval)
return lastTimerCount - 1
})
}, 1000) //each count lasts for a second
//cleanup the interval on complete
return () => clearInterval(interval)
}, []);
使用状态变量 timerCount 作为:<Text>{timerCount}</Text>
关于react-native - react-native 中的倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695887/