【问题标题】:React - Async background API callsReact - 异步后台 API 调用
【发布时间】:2018-02-04 10:03:37
【问题描述】:

我们的团队正在开发一个网络应用/游戏,如果条件为真,我们希望每 8 秒调用一次 API。 此过程由启动填充方法的按钮触发

async autoLoad() {
        const timer = await 8; 
        console.log('debug consolelog')           
        const result = await this.UpdateProfile();
    }

togglePopulate() {
        const status = this.state.autoLoad;
        if (status === true) {
            this.setState({ autoLoad: false });
        } else {
            this.setState({ autoLoad: true });
            this.autoLoad();
        }
    }

我们的理解是,这将每 8 秒在后台运行一次“UpdateProfile()”函数。然而,结果是我们的整个网页被锁定并且 UpdateProfile(或调试 console.log)没有运行。

有人知道我们做错了什么吗? (或者如果我们尝试做的事情是可能的?)

【问题讨论】:

    标签: javascript reactjs async-await


    【解决方案1】:

    无意冒犯,但如果您尝试通过 const timer = await 8 设置计时器,我认为您可能误解了异步等待的工作原理。您可能想阅读一些准确描述 Async Await 返回给您的文章的文章。

    但是,设置要在计时器上调用的函数实际上有点与 React 混淆。我觉得这更多的是你遇到的问题。我希望这个例子对你有所帮助。

    class Example extends React.Component {
      constructor(props) {
        super(props)
    
        this.state = {
          interval: null
        }
        this.enableAutoload = this.enableAutoload.bind(this)
        this.disableAutoload = this.disableAutoload.bind(this)
      }
    
      enableAutoload() {
        const setTimer = window.setInterval(() => {
                          this.iRunEveryEightSeconds()
                         }, 8000)
        this.setState({ interval: setTimer })
      }
    
      disableAutoload() {
        console.log('Clearing the timer from state...')
        const clearTimer = window.clearInterval(this.state.interval)
        this.setState({ interval: clearTimer })
      }
    
      iRunEveryEightSeconds() {
        console.log('Hello There.')
      }
    
      render() {
        return (
          <div className="example">
            Example API Call Every 8 Seconds
    
            <button onClick={this.enableAutoload} className="enable">
              Enable Autoload
            </button>
    
            <button onClick={this.disableAutoload} className="disable">
              Disable Autoload
            </button>
          </div>
        )
      }
    }
    
    ReactDOM.render (
      <Example />,
      document.querySelector('#app')
    )
    

    我知道您需要在满足特定条件时运行此 API 调用。您可以使用此示例了解如何在条件为真时将计时器设置为状态,并在其评估为假时清除状态间隔。单击启用按钮和单击禁用按钮后,请务必检查下面 Codepen 示例中的控制台。单击禁用按钮后,“Hello There”将每 8 秒停止打印一次。

    包含的Codepen 示例将进一步帮助您。有什么问题,欢迎提问!

    【讨论】:

    • 这解决了我们的问题,使我们免于更多令人沮丧的故障排除时间。感谢您的帮助!
    • 没问题。很高兴为您提供帮助 =)
    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2019-07-05
    • 2022-01-20
    相关资源
    最近更新 更多