gpt4 book ai didi

javascript - 在 ReactJS 中安排 API 调用

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:14 24 4
gpt4 key购买 nike

我有一个基于 React 的 Web 应用程序,它从 Jenkins API 检索数据。在 componentDidMount() 函数中,我调用了第一个启动 API 调用流程的 API。然后我将使用来自 API 的数据渲染组件。

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

我们能否安排 React 在一天中的特定时间调用这些 API 并获取之前提到的更新数据?或者刷新浏览器等会产生新的 API 数据?我是 React 的新手,非常感谢您提出的实现这一目标的建议。

最佳答案

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

就像:

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
}

换句话说,它将:

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

无论您何时启动 React 应用程序,这都会起作用。

关于javascript - 在 ReactJS 中安排 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262655/

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