小编典典

每隔x秒轮询api与react

reactjs

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

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 }));
  }

这是正确的方法吗?


阅读 1105

收藏
2020-07-22

共1个答案

小编典典

好吧,由于您只有一个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调用是异步的,这可能会导致相同的问题。使其可取消,fetch在不完整的情况下取消。

我希望这有帮助。

2020-07-22