首页 > 解决方案 > 使用 react 轮询 API

问题描述

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

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

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

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

componentDidMount它不喜欢我这样做

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

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

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

标签: javascriptreactjsapipolling

解决方案


我认为你应该检查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只是为了允许配置轮询时间。


推荐阅读