首页 > 解决方案 > Redux Action 中的轮询

问题描述

我正在尝试在我的一项 redux 操作中进行轮询。以下是我的动作函数。它似乎正在工作,但是当状态不再“更新”并且数据出现时,它仍然运行循环。不知道为什么停止不起作用。

export const getVisitSummary = () => async (dispatch: Function) => {
  let res = await dispatch({
    type: GET_VISIT_SUMMARY,
    payload: {
      client: 'visitSummary',
      request: {
        method: 'get',
        url: '/visit-summaries'
      }
    }
  });

  const timelineStatus = res.payload.headers['x-timeline-status'];
  const wait = (ms: number) => new Promise(r => setTimeout(r, ms));

  // Not currently updating
  if (timelineStatus !== 'updating') {
    return res;
  }

  // Start polling
  dispatch({ type: START_POLLING });

  while (true) {
    // wait 10 seconds
    await wait(10000);

    res = await dispatch({
      type: GET_VISIT_SUMMARY,
      payload: {
        client: 'visitSummary',
        request: {
          method: 'get',
          url: '/visit-summaries'
        }
      }
    });

    if (timelineStatus !== 'updating') {
      break;
    }
  }

  dispatch({ type: STOP_POLLING });
};

任何帮助都会很有用!

标签: javascriptreactjsreact-nativereduxpolling

解决方案


将@azundo 的评论翻译成答案:

export const getVisitSummary = () => async (dispatch: Function) => {
  let res = await dispatch({
    type: GET_VISIT_SUMMARY,
    payload: {
      client: 'visitSummary',
      request: {
        method: 'get',
        url: '/visit-summaries'
      }
    }
  });

  /***************************************/
  /*** 1: Change from `const` to `let` ***/
  /***************************************/
  let timelineStatus = res.payload.headers['x-timeline-status'];
  const wait = (ms: number) => new Promise(r => setTimeout(r, ms));

  // Not currently updating
  if (timelineStatus !== 'updating') {
    return res;
  }

  // Start polling
  dispatch({ type: START_POLLING });

  while (true) {
    // wait 10 seconds
    await wait(10000);

    res = await dispatch({
      type: GET_VISIT_SUMMARY,
      payload: {
        client: 'visitSummary',
        request: {
          method: 'get',
          url: '/visit-summaries'
        }
      }
    });
    /*********************************************************/
    /*** 2: Use updated `timelineStatus` in if conditional ***/
    /*********************************************************/
    timelineStatus = res.payload.headers['x-timeline-status'];
    if (timelineStatus !== 'updating') {
      break;
    }
  }

  dispatch({ type: STOP_POLLING });
};


推荐阅读