在ReactJS中安排API调用

cha*_*nae 4 javascript api jenkins typescript reactjs

我有一个基于React的Web应用程序,可从Jenkins API检索数据。在componentDidMount()函数期间,我正在调用第一个API,这将启动API调用流程。然后,我将使用API​​中的数据来呈现组件。

Jenkins服务器每天早上7点开始构建每个项目。因此,我想每天晚上8点左右从React调用这些API。

我们是否可以安排React来调用这些API并获取它在一天中特定时间的更新数据?还是刷新浏览器等会产生新的API数据?我是React的新手,非常感谢您的建议。

Chr*_*ris 5

您在中正确使用了API调用componentDidMount()。您可以setTimeout()在坐骑上使用,直到20:00,然后setInterval()每隔24小时再次触发该事件。

像这样:

componentDidMount() {
  const currentTime = new Date().getTime();  //current unix timestamp
  const execTime = new Date().setHours(20,0,0,0);  //API call time = today at 20:00
  let timeLeft;
  if(currentTime < execTime) {
    //it's currently earlier than 20:00
    timeLeft = execTime - currTime;
  } else {
    //it's currently later than 20:00, schedule for tomorrow at 20:00
    timeLeft = execTime + 86400000 - currentTime
  }
  setTimeout(function() {
    setInterval(function() {

      //your code

    }, 86400000);  //repeat every 24h
  }, timeLeft);  //wait until 20:00 as calculated above
}
Run Code Online (Sandbox Code Playgroud)

换句话说,它将:

  1. 计算现在和下一个20:00钟点之间的时差。
  2. 等到20:00setTimeout()
  3. 将触发器设置为恰好24小时(即86400000 ms)以重复其中的代码setInterval()

无论何时启动React应用程序,它都将起作用。