首页 > 解决方案 > 如果找不到页面,Redux Saga 将继续循环

问题描述

这是我的rootSaga.ts

import { all } from 'redux-saga/effects';

import { Watcher } from '../sagas';

export default function* rootSaga() {
  yield all([Watcher()]);
}

我的API axios

 import axios from 'axios';


const fetchAPI = () => {
  return axios.get('https://sample404Case');
};

export default fetchAPI;

这是我的Saga

export function* Watcher() {
  yield takeLatest(actionIds.FETCH_SAMPLE_REQUEST_START, fetchSample);
}

function* fetchSample() {
  try {
    console.log('generated');
    const generatedSample = yield call(FetchSample);
    console.log(generatedSample);
    yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_SUCCESSFUL, payload: generatedSample.data });
  } catch (error) {
    console.log(error);
    yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_START, error });
  }
}

注意我故意想要一个 404 错误,但我的问题是它会产生一个 continue 循环,这会使我的页面冻结。

一旦出现错误,有没有办法停止传奇?

标签: reactjstypescriptredux-saga

解决方案


当你有一个错误导致它进入无限循环时,你正在重新启动 saga(因为你希望它出现 404 错误):

  catch (error) {
    console.log(error);
    yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_START, error });
  }

您应该为失败状态添加另一个操作(例如:FETCH_SAMPLE_REQUEST_FAILED)并在 catch 内调度它


推荐阅读