react封装倒计时定时器
生活随笔
收集整理的這篇文章主要介紹了
react封装倒计时定时器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
準備工作:
1.在state中定義倒計時時間;
constructor(props){super(props);this.state={time: 60, } }2.添加定時器方法;
// 倒計時 time = () => {// 清除可能存在的定時器clearInterval(this.timer)// 創建(重新賦值)定時器this.timer = setInterval(()=>{// 當前時間回顯-1this.setState({time:this.state.time-1},()=>{// 判斷修改后時間是否小于1達到最小時間if(this.state.time <= 0){// 清除定時器clearInterval(this.timer)// 結束定時器循環return}// 循環自調用this.time()})},1000) }3.在組件卸載時清除定時器
componentWillUnmount(){clearInterval(this.timer) }使用:
在需要使用的地方直接調用time方法即可;
ps:頁面加載完成后調用案例如下
componentDidMount(){this.time() }?
總結
以上是生活随笔為你收集整理的react封装倒计时定时器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 产品的波士顿矩阵分析
- 下一篇: 最赏识王小川的,还是马化腾