React Native轮询

3

我正在尝试编写一些API轮询代码,以下是目前的代码:

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);
}

这段代码可以工作,但是问题在于它是否由于递归而存在性能下降?有没有更好的解决方案来进行 React Native 中的轮询?感谢帮助 :)

2个回答

2

不确定递归在这里的性能影响(甚至不确定 setTimeout 闭包是否算作递归),但是你可以使用 setInterval 每隔 10 分钟调用一次轮询方法,而无需链接调用。当你想要停止时,别忘了使用 clearInterval

例如:

async retrieveNotifications() {
    const res = await fetch(url)
    if (res.status === 200) {
        this.props.setNotifications(res.data)
    }
}

//inside some class method
setInterval(this.retrieveNotifications, 600000);

有没有一种简单的方法可以使用async await?我不喜欢使用promises ^^ - Kape
我认为它会正常工作... async/await 关注的是方法内部发生的事情。间隔不会等待它,但是方法内部的代码应该像以前一样运行。上面添加了一个示例。 - bmovement
我非常感谢你的帮助,你的代码几乎起作用了,但是它以某种方式返回了未定义的 res.data,像这样。为了使它起作用,我不得不将 retrieveNotifications 更改为一个 fat arrow 函数。我会发布可工作的代码,以便于遇到同样问题的人参考,这看起来很不错,就像你建议的那样。 - Kape
详细了解 setInterval() 和 clearInterval() 的用法,请参考此文。使用 React Hooks 将会更加优化。 https://overreacted.io/making-setinterval-declarative-with-react-hooks/ - Sikandar Khan

0

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

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)
  }
}

1
是的,这会导致性能问题,所以我最终使用了以下的npm: react-native-background-timer。 - Kape
谢谢@Kape。那很有帮助。 - Christopher Chalfant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接