apr*_*eda 4 reactjs redux redux-saga react-redux
在我的应用程序中我有以下代码
componentWillUpdate(nextProps) {
if(nextProps.posts.request.status === 'failed') {
let timer = null;
timer = setTimeout(() => {
if(this.props.posts.request.timeOut == 1) {
clearTimeout(timer);
this.props.fetchData({
page: this.props.posts.request.page
});
} else {
this.props.decreaseTimeOut();
}
}, 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
它的作用是,当 API 请求遇到错误,可能是因为没有互联网连接(就像 facebook 的聊天方式一样),或者后端出现错误时,它会在五秒后重试,但setTimeout
需要每隔一秒设置一次以更新存储的一部分,即行this.props.decreaseTimeOut();
,但如果计数器已用完,五秒过去了,则将if block
运行并重新分派fetchData action
.
它工作得很好,我对它没有任何问题,至少在功能方面,但在代码设计方面,我知道它是一个side-effect
并且不应该在我的反应组件中处理,因为我使用的是 redux- saga (但我是 redux-saga 的新手,我今天才学会),我想将该功能转换为 saga,我不太清楚如何做到这一点,这是我fetchData saga
的道路。
import {
take,
call,
put
} from 'redux-saga/effects';
import axios from 'axios';
export default function* fetchData() {
while(true) {
try {
let action = yield take('FETCH_DATA_START');
let response = yield call(axios.get, '/posts/' + action.payload.page);
yield put({ type: 'FETCH_DATA_SUCCESS', items: [...response.data.items] });
} catch(err) {
yield put({ type: 'FETCH_DATA_FAILED', timeOut: 5 });
}
}
}
Run Code Online (Sandbox Code Playgroud)
对代码的干扰较小的是使用redux-saga 的延迟承诺:
catch(err) {
yield put({ type: 'FETCH_DATA_FAILED'});
for (let i = 0; i < 5; i++) {
yield call(delay, 1000);
yield put(/*Action for the timeout/*);
}
}
Run Code Online (Sandbox Code Playgroud)
但我会以这种方式重构你的代码:
function* fetchData(action) {
try {
let response = yield call(axios.get, '/posts/' + action.payload.page);
yield put({ type: 'FETCH_DATA_SUCCESS', items:[...response.data.items] });
} catch(err) {
yield put({ type: 'FETCH_DATA_FAILED'});
yield put({ type: 'SET_TIMEOUT_SAGA', time: 5 });
}
}
}
function *setTimeoutsaga(action) {
yield put({type: 'SET_STATE_TIMEOUT', time: action.time}); // Action that update your state
yield call(delay, 1000);
// Here you use a selector which take the value if is disconnected:
// https://redux-saga.js.org/docs/api/#selectselector-args
const isStillDisconnected = select()
if (isStillDisconnected) {
yield put({type: 'SET_TIMEOUT_SAGA', time: action.time - 1});
}
function *fetchDataWatchers() {
yield takeEvery('FETCH_DATA_START', fetchData);
yield takeEvery('SET_TIMEOUT_SAGA', setTimeoutSaga);
// You can insert here as many watcher you want
}
export default [fetchDataWatchers]; // You will use run saga for registering this collection of watchers
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6836 次 |
最近记录: |