定时器轮询请求,清理定时器

bug以下:
unReadMsgList请求10秒一次,getBmUpdateSettingsListByUserId5秒一次,本应该两个unReadMsgList之间出现两次getBmUpdateSettingsListByUserId,可是实际出现了6个getBmUpdateSettingsListByUserId(如图),
是因为进入页面,调用了一次getBmUpdateSettingsListByUserId请求,没清理定时器,
运行操做的时候,调用了一次getBmUpdateSettingsListByUserId请求,没清理定时器,
删除操做的时候,调用了一次getBmUpdateSettingsListByUserId请求,没清理定时器,就出现了三倍的数量函数

image.png

componentDidMount() {
  this.requestList(); // 请求模型更新表格数据
}
// 查询列表
requestList = () => {
  _getBmUpdateSettingsListByUserId({
   // 获取列表请求
  }).finally(()=>{ this.timer = setTimeout(()=>{
      this.requestList()
    },5000)})
}
 
// 删除请求成功后,请求一次列表
DeleteAlert({
  // 删除请求
}).then(
   this.requestList()
)

// 运行(添加)请求成功后,请求一次列表
_addBmUpdateSettings({
   // 运行(添加)请求
}).then(
  this.requestList()
)

// 离开页面的钩子,清理定时器
componentWillUnmount () {
  clearTimeout(this.timer);
}

解决方案以下: this.requestList()函数中加入清理定时器,其他不变this

requestList = () => {
  clearTimeout(this.timer); // 清理以前的定时器队列
  _getBmUpdateSettingsListByUserId({
   // 获取列表请求
  }).finally(()=>{ this.timer = setTimeout(()=>{
     this.requestList()
  },5000)})
}

image.png

相关文章
相关标签/搜索