javascript - 使用 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,或者这是正确的方法吗?
解决方案
我认为你应该检查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只是为了允许配置轮询时间。
推荐阅读
- iis - 访问从单独机器上的主机文件路由的主机名
- kendo-ui - 如何在列模板中使用剑道网格聚合值
- android - Android - 在不拨打网络电话的情况下检查活动的 Internet 连接
- mysql - WHERE NOT EXISTS 在尝试基于独立于另一个表的条件插入时不起作用
- audio - 使用 ffmpeg 将 wav 文件拆分为多个重叠的 .wav 文件
- javascript - 将 img 的值分配给 value 属性
- git - git stash 没有正确存储更改
- asp.net - 如何保护 ASP .NET WebAPI 2.0 多租户应用程序?
- c++ - c++ 正则表达式没有按预期工作(regex_search)
- javascript - 带有 HTML5 `pattern` 属性的 `.checkValidity()` 总是返回 true