每隔x秒轮询api与react [英] polling api every x seconds with react
问题描述
我必须每隔一两秒钟监视屏幕上的一些数据更新信息. 我发现使用此实现的方式:
I have to monitoring some data update info on the screen each one or two seconds. The way I figured that was using this implementation:
componentDidMount() {
this.timer = setInterval(()=> this.getItems(), 1000);
}
componentWillUnmount() {
this.timer = null;
}
getItems() {
fetch(this.getEndpoint('api url endpoint"))
.then(result => result.json())
.then(result => this.setState({ items: result }));
}
这是正确的方法吗?
推荐答案
好吧,由于您只有API,并且无法控制它才能更改为使用套接字,因此唯一的方法是轮询
Well, since you have only an API and don't have control over it in order to change it to use sockets, the only way you have is to poll.
根据您的民意测验,您正在采取体面的方法.但是上面的代码有一个陷阱.
As per your polling is concerned, you're doing the decent approach. But there is one catch in your code above.
componentDidMount() {
this.timer = setInterval(()=> this.getItems(), 1000);
}
componentWillUnmount() {
this.timer = null; // here...
}
getItems() {
fetch(this.getEndpoint('api url endpoint"))
.then(result => result.json())
.then(result => this.setState({ items: result }));
}
这里的问题是,一旦卸下组件,尽管对存储在this.timer
中的间隔的引用设置为null
,它仍未停止.即使卸载了组件,间隔也会继续调用处理程序,并且会尝试setState
在不再存在的组件中.
The issue here is that once your component unmounts, though the reference to interval that you stored in this.timer
is set to null
, it is not stopped yet. The interval will keep invoking the handler even after your component has been unmounted and will try to setState
in a component which no longer exists.
要正确处理此问题,请先使用clearInterval(this.timer)
,然后再设置this.timer = null
.
To handle it properly use clearInterval(this.timer)
first and then set this.timer = null
.
此外,fetch
调用是异步的,这可能会导致相同的问题.将其设置为可取消,如果fetch
不完整,请取消.
Also, the fetch
call is asynchronous, which might cause the same issue. Make it cancelable and cancel if any fetch
is incomplete.
我希望这会有所帮助.
这篇关于每隔x秒轮询api与react的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!