首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Native Polling

React Native Polling
EN

Stack Overflow用户
提问于 2019-04-23 03:51:10
回答 2查看 3.7K关注 0票数 2

我正在尝试实现一些api轮询代码,这是我到目前为止所得到的:

代码语言:javascript
复制
async retrieveNotifications() {
  const res = await fetch(url)
  if (res.status === 200) {
    this.props.setNotifications(res.data)
  }
  setTimeout(() => {
    this.retrieveNotifications()
    // polling in 10 min cycles
  }, 600000);
}

代码可以工作,但是问题是,这是否因为它的递归而有任何性能下降?有没有人知道rn中更好的轮询解决方案?感谢您的帮助:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-23 03:54:38

这里不确定递归的性能影响(或者甚至不确定setTimeout闭包是否准确地算作递归),但是您可以使用setInterval每10分钟调用一次轮询方法,而不需要以菊花链形式调用这些调用。当你想让clearInterval停止的时候,不要忘记使用它!

例如:

代码语言:javascript
复制
async retrieveNotifications() {
    const res = await fetch(url)
    if (res.status === 200) {
        this.props.setNotifications(res.data)
    }
}

//inside some class method
setInterval(this.retrieveNotifications, 600000);
票数 2
EN

Stack Overflow用户

发布于 2019-04-23 04:38:53

这是改进后的代码,建议的形式为@bmovement,感谢您的帮助:D

代码语言:javascript
复制
constructor() {
  super()
  // polling in 10 min cycles
  this.interval = setInterval(this.retrieveNotifications, 600000)
}

componentDidMount() {
  this.retrieveNotifications()
}

componentWillUnmount() {
  clearInterval(this.interval);
}

retrieveNotifications = async () => {
  const res = await fetch(url)
  if (res.status === 200) {
    this.props.setNotifications(res.data)
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55800270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档