簡體   English   中英

使用 redux-saga 進行輪詢

[英]Polling with redux-saga

我試圖用這個頁面上的信息解決輪詢: https://bigbite.net/polling-with-redux/

// inside a saga
import { delay } from 'redux-saga';
...

export function* pollStuffSaga() {
  while (true) {
    try {
      const response = yield call(fetchStuff);
      const items = handleResponse(response);
      yield put(onFetchStuffSuccess(items));
      yield delay(30000); // 30 sec
    } catch (e) {
      yield put(onFetchStuffFailure(e));
    }
  }
}

function* pollWatcherSaga() {
  while (true) {
    yield take(START_POLLING); // I call start polling from componentDidMount
    yield race([call(pollArchiveSaga), take(STOP_POLLING)]); // And I call stop polling from componentWillUnmount
  }
}

export default function* rootSaga() {
  yield call(pollWatcherSaga); // fired when saga is injected
}

我現在遇到的問題是我在.network 中看到我的服務被調用了太多次。 它一直被調用。 我的延遲不應該阻止它在下一輪內調用我的 fetchStuff 嗎? 它不應該在代碼繼續之前等待 30 秒嗎?

我對問題的界限做了評論。 當我修復我的“自制方法”,handleResponse(響應),然后我的拉動邏輯工作。 所以只要看看我如何在該方法中處理我的響應,這段代碼將與相應的reducer和actions等一起使用:

import { delay } from 'redux-saga';
...

export function* pollStuffSaga() {
  while (true) {
    try {
      const response = yield call(fetchStuff);
      const items = handleResponse(response); // The problem was inside this function
      yield put(onFetchStuffSuccess(items));
      yield delay(30000);
    } catch (e) {
      yield put(onFetchStuffFailure(e));
    }
  }
}

function* pollWatcherSaga() {
  while (true) {
    yield take(START_POLLING);
    yield race([call(pollArchiveSaga), take(STOP_POLLING)]);
  }
}

export default function* rootSaga() {
  yield call(pollWatcherSaga);
}

我遇到過同樣的問題。 我將延遲 function 從“redux-saga/effects”更改為我自己的延遲 function,它起作用了。

const delay = (ms) => new Promise((res) => setTimeout(res, ms));

並像這樣使用它:

yield delay(4000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM