1. 需求:
由於數據計算量比較大,所以接口請求返回數據可能會比較慢,這時候咋整勒。為了提高用戶體驗,想到了前端定時刷新,定時器走起~
2. 定時請求接口
a. 先定義個全局的定時器,取名timer
b.
// 組件卸載時清空定時器 componentWillUnmount() { clearInterval(this.timer) } timedRefresh = () => { clearInterval(this.timer) if ( 我是條件 ) { this.timer = setInterval(() => { fetchSomething(params1, params2) // 每隔3s請求一次接口 }, 3000) } else { clearInterval(this.timer) // 取消定時器 } }
3. 定時刷新頁面
a. 先定義個全局的定時器,取名timer
b.
// 組件卸載時清空定時器 componentWillUnmount() { clearInterval(this.timer) } timedRefresh = () => { clearInterval(this.timer) if ( 我是條件 ) { this.timer = setInterval(() => { window.location.reload() // 每隔3s刷新整個頁面 }, 3000) } else { clearInterval(this.timer) // 取消定時器 } }