反应本机轮询

问题描述 投票:0回答:2

我正在尝试实现一些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);
}

代码是有效的,但问题是,如果它有任何性能缺点,因为它的递归?有没有人知道更好的rn轮询解决方案?谢谢您的帮助 :)

react-native polling
2个回答
0
投票

这里不确定递归的性能影响(或者即使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);

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)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.