在处理Redux操作时,超时问题通常是指在某个异步操作(如API请求)完成之前,如果等待时间过长,我们希望采取一些措施,比如取消请求或者显示一个错误消息。以下是解决这个问题的几种方法:
function fetchUser(timeout = 5000) {
return (dispatch) => {
const controller = new AbortController();
const signal = controller.signal;
const timeoutId = setTimeout(() => {
controller.abort();
}, timeout);
fetch('/api/user', { signal })
.then(response => response.json())
.then(data => {
clearTimeout(timeoutId);
dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
})
.catch(error => {
if (error.name === 'AbortError') {
dispatch({ type: 'FETCH_USER_TIMEOUT' });
} else {
dispatch({ type: 'FETCH_USER_FAILURE', error });
}
});
};
}
import { call, put, takeLatest, race } from 'redux-saga/effects';
function* fetchUser(action) {
try {
const { response, timeout } = yield race({
response: call(fetch, '/api/user'),
timeout: delay(5000)
});
if (response) {
const user = yield response.json();
yield put({ type: 'FETCH_USER_SUCCESS', payload: user });
} else {
yield put({ type: 'FETCH_USER_TIMEOUT' });
}
} catch (error) {
yield put({ type: 'FETCH_USER_FAILURE', error });
}
}
function* watchFetchUser() {
yield takeLatest('FETCH_USER_REQUEST', fetchUser);
}
import { ofType } from 'redux-observable';
import { switchMap, timeout, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
const fetchUserEpic = (action$) => action$.pipe(
ofType('FETCH_USER_REQUEST'),
switchMap(() =>
fetch('/api/user').then(response => response.json()).pipe(
timeout(5000),
catchError(error => of({ type: 'FETCH_USER_FAILURE', error }))
)
)
);
以上方法可以帮助你在Redux操作中处理超时问题。选择哪种方法取决于你的具体需求和项目的复杂性。
领取专属 10元无门槛券
手把手带您无忧上云