【问题标题】:Delay a loop with timeout in react js在反应js中延迟一个超时循环
【发布时间】:2022-01-16 23:10:11
【问题描述】:

如果请求仍在处理中,我正在尝试循环数组并延迟循环,并在请求完成后继续循环。

这是我的代码的样子

// request is from redux
for (var i = 0; i < request.length; i++) {
    let k = i;
    setTimeout(function () {
        // requestInProgress came from redux so it will re-render when the value is updated
        if(!requestInProgress){
            // proceed the loop
        } else {
            // I want to delay the loop by giving more timeout but not sure how it should be done here
        }
    }, 5000 * (k + 1));
}

目前,我在 else 声明中没有任何内容。我只是想在那里增加更多的时间延迟,但不确定是否可以这样做。任何帮助将非常感激。谢谢。

【问题讨论】:

  • 我认为您不会在循环中获得 requestInProgress 的更新值。当你的循环开始时,requestInProgress 有一个值,可能是truefalse。在循环的其余部分中,它将保持该值。
  • 我明白了。我不知道那件事。您对我应该应用什么结构来执行类似于可以从 redux 读取新值更新的方法有什么建议吗?
  • 阅读这篇文章,这对你来说不是确切的解决方案,但会帮助你 - stackoverflow.com/questions/37576685/…
  • 你使用的是 React Hooks 还是基于类的组件?

标签: reactjs for-loop settimeout


【解决方案1】:

如果您在运行代码之前尝试等待您的请求,您可以尝试使用异步等待。虽然我不知道 requestInProgress 是如何传递给你的代码的。

  const get_data = async () => {
    const response = await fetch('http://your-request')
    console.log(`code after request, response: ${response}`)
    //code here
  }

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
相关资源
最近更新 更多