当屏幕以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);
}
Run Code Online (Sandbox Code Playgroud)
Moh*_*faq 16
在你的代码的setTimeout被称为在C omponentDidMount和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>
)
}
Run Code Online (Sandbox Code Playgroud)
更新Hooks(使用useEffect)版本以在 react-native 中使用setInterval进行倒计时:
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)
}, []);
Run Code Online (Sandbox Code Playgroud)
使用状态变量timerCount作为:<Text>{timerCount}</Text>
归档时间: |
|
查看次数: |
11284 次 |
最近记录: |