【问题标题】:Polling an API with react使用 react 轮询 API
【发布时间】:2018-08-20 09:58:16
【问题描述】:

我需要在 React 中每 30 秒轮询一次 API 以获取响应

我正在考虑调用这个方法:

poll() {
    setTimeout(() => {
        console.log('polling') // would hit the API here
    }, 100)
}

componentDidMount 里面,然后在里面做一个三元组什么的

但是在componentDidMount 它不喜欢我这样做

this.props.loading ? this.poll() : null

说一些关于预期功能但看到表达(linting 错误)

如何轮询 API,或者这是正确的方法吗?

【问题讨论】:

  • 请分享完整的生命周期代码和构造函数

标签: javascript reactjs api polling


【解决方案1】:

我认为你应该检查 poll() 方法中的 props.loading,这样:

poll () {
    // you should keep track of the timeout scheduled and 
    // provide a cleanup if needed
    this.state.polling && clearTimeout(this.state.polling)

    if (!this.props.loading) {            
        this.setState({ polling: false })
        return
    }

    const polling = setTimeout(() => {
        // stuff here

        // as last step you should call poll() method again
        // if you have asyncronous code you should not call it
        // as a step of your async flow, as it has already is 
        // time period with setTimeout
        this.poll()
    }
    , this.state.pollingIntervall)

    this.setState({
        polling
    })
}

那么你只需要调用poll()方法来启动它。

添加了 state.pollingIntervall 只是为了允许配置轮询时间。

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多