我必须每隔一两秒监视屏幕上的一些数据更新信息。
我认为使用此实现的方式:
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 并且无法控制它以将其更改为使用套接字,因此您唯一的方法就是轮询。
根据您的民意调查,您正在采取正确的做法。但上面的代码中有一个问题。
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
在不再存在的组件中。
要正确处理它,请使用clearInterval(this.timer)
首先然后设置this.timer = null
.
另外,fetch
调用是异步的,这可能会导致同样的问题。做了可取消的 https://developers.google.com/web/updates/2017/09/abortable-fetch并取消(如有)fetch
是不完整的。
我希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)