在ReactJs上每5秒执行一次Get请求

时间:2019-11-14 12:38:59

标签: javascript reactjs

尽管尝试使用setTimeout函数,但我尝试每5秒从我的reactjs应用向api执行一次http get请求,但是在开始的5秒之后,所有请求都已完成。

getPerson = (url) => {
  axios.get(url)
    .then(response => {
      let person = {};
      person.id = response.data.id;
      person.name = response.data.name;
      person.type = response.data.type;
      this.state.persons.push(person);
      this.setState({ persons: this.state.persons });
    });
}

componentDidMount() {
  for(var i = 1; i < 11; i++){
    this.getPerson(this.apiUrl + i);
    setTimeout(function () {
      console.log("waiting for the next call.");
    }, 5000);
  }
}

2 个答案:

答案 0 :(得分:0)

  componentDidMount() {
    let i = 0;
    let interval = setInterval(() => {
      if (i<11) {
        this.getPerson(this.apiUrl + i);
        i++;
        console.log("waiting for the next call.");
      }
      else {
        clearInterval(interval)
      }

    }, 5000);
  }

为此,您应该使用setInterval(),而不是setTimeout()

编辑:如果您因某种原因无法访问this中的setInterval(),即使您应该使用箭头功能,也可以使用变通方法< / p>

let that = this,然后使用that.getPerson(that.apiUrl + i);

调用您的方法

答案 1 :(得分:0)

仍然无法从匿名块函数内部访问“此”对象。

  getPerson = (url) => {
axios.get(url)
  .then(response => {
    let person = {};
    person.id = response.data.id;
    person.name = response.data.name;
    this.state.loadedPersons.push(person);
    this.setState({ loadedPersons: this.state.loadedPersons });
  });}


componentDidMount() {
for (var j = 1; j < 152; j++) {
  this.getPerson(this.apiUrl + j);
}
let i = 1;
let that = this.state;
console.log("That out of in interval:" + that);
let interval = setInterval(function (that) {
  console.log("That in interval:" + that);
  if ((i<152))
    that.persons.push(that.loadedPersons[i]);
    i++;
  }
  else {
    clearInterval(interval)
  }

}, 5000);

}

控制台输出:

超出间隔:[对象对象]

间隔时间:未定义