如果找不到页面,Redux Saga 会继续循环
Redux Saga continues loop if Page not Found
这是我的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 错误,但我的问题是它会继续循环,导致我的页面冻结。
一旦出错一次,有没有办法停止传奇?
您在遇到错误时重新启动 saga,导致它进入无限循环(因为您希望它出现 404 错误):
catch (error) {
console.log(error);
yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_START, error });
}
您应该为失败状态添加另一个操作(例如:FETCH_SAMPLE_REQUEST_FAILED)并在 catch
中调度它
这是我的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 错误,但我的问题是它会继续循环,导致我的页面冻结。
一旦出错一次,有没有办法停止传奇?
您在遇到错误时重新启动 saga,导致它进入无限循环(因为您希望它出现 404 错误):
catch (error) {
console.log(error);
yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_START, error });
}
您应该为失败状态添加另一个操作(例如:FETCH_SAMPLE_REQUEST_FAILED)并在 catch
中调度它