gpt4 book ai didi

javascript - 每 x 秒使用 React 轮询一次 API

转载 作者:行者123 更新时间:2023-12-03 12:57:31 24 4
gpt4 key购买 nike

我必须每隔一两秒监视屏幕上的一些数据更新信息。我认为使用此实现的方式:

    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 调用是异步的,这可能会导致相同的问题。做到cancelable如果任何 fetch 不完整,则取消。

我希望这会有所帮助。

关于javascript - 每 x 秒使用 React 轮询一次 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com