我正在尝试实现一些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中更好的轮询解决方案?感谢您的帮助:)
发布于 2019-04-23 03:54:38
这里不确定递归的性能影响(或者甚至不确定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);发布于 2019-04-23 04:38:53
这是改进后的代码,建议的形式为@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)
}
}https://stackoverflow.com/questions/55800270
复制相似问题