You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Redux应用中如何实现服务端数据的定时重复获取?

React+Redux文档表格的定时刷新实现问题

我正在开发一个基于React + Redux的单页应用,页面里有个文档表格,需求是每20秒自动刷新一次数据。

我清楚JavaScript里有setTimeout和setInterval这两个定时器函数,但我觉得setInterval并不适合我的场景——它只会机械地每隔固定时间调用函数,完全不管之前的请求有没有得到响应(后端处理请求是需要耗时的),这样很可能导致请求堆积。所以我选择用setTimeout来实现逻辑,下面是我简化后的组件代码:

import {connect} from 'react-redux';
const { DATA_REFRESH_TIMEOUT, RETRY_REFRESH_TIMEOUT } = __ENVIRONMENT_CONFIG__;
@connect(
  (state) => ({
    documents: state.documents.documents,
    loadingDocuments: state.documents.loading
  }),
  (dispatch) => bindActionCreators(
    { dispatchLoadDocuments: loadDocuments },
    dispatch
  )
)
export default class Dashboard extends Component {
  documentasTimeoutId;
  constructor(props) {
    super(props);
    this.state = { documentType: null };
  }
  ....
  handleDocumentTypeChange = (event, documentType) => {
    //如果文档类型改变,我必须终止当前计时器并立即获取对应类型的文档
    this.setState({documentType: documentType});
    this.clearTimeoutAndGetDocuments(documentType);
  };
  getDocuments = (documentType) => {
    //此处检查文档加载状态,如果正在加载,则等待一段时间后重试加载
    const{ loadingDocuments } = this.props;
    if(!loadingDocuments) {
      this.props.dispatchLoadDocuments(documentType);
    } else {
      this.documentasTimeoutId =...
    }
  };
}

这里还有两个关键的业务逻辑需要处理:

  • 当用户切换文档类型时,必须立刻终止当前的计时器,并且马上获取对应类型的文档数据
  • 在获取文档数据前,会先检查Redux里的加载状态,如果当前正在加载中,就会等待一段时间后重试

内容的提问来源于stack exchange,提问作者Oblomingo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:44:40