在我的React应用程序中,有一个Saga调用后端API来检索某些图表数据。请阅读源代码在Redux-saga中,如何在一个传奇故事中调用传奇?
function fetchData() {
return fetch(`${config.base}dashboard_charts.json`)
.then((response) => {
if (response.status === 200) {
return response.json();
} else if (response.status === 403) {
return 'logon';
}
});
}
function * getData (action) {
try {
const charts = yield call(fetchData);
if (charts === 'logon') {
yield logon();
} else {
yield put({ type: UPDATE_DASHBOARD_CHART, charts });
}
} catch (error) {
yield put({ type: UPDATE_DASHBOARD_CHART, charts: [] });
}
}
function * logon (action) {
yield auth();
}
export default function * portfolio() {
yield [
takeEvery(FETCH_DASHBOARD_CHART, getData)
];
};
有反对的功能fetchData HTTP响应状态的检查,如果状态为200,然后直接返回响应。但是,如果服务器端返回403,这意味着客户端需要进行身份验证,因此该程序将转到auth()并执行登录。
但是,http响应状态代码检查在某种程度上是适用于所有API调用的通用功能。所以我不想在每个传奇中重复这种代码。为此,我写了一个服务“ResponseHandler所”进行分组响应代码检查里面是这样的:
export default function responseHandler (resp) {
if (resp.status === 401 || resp.status === 403) {
yield auth();
} else if (resp.status === 200) {
} else {
console.log('error handling');
}
};
它会叫的fetchData
return fetch(`${config.base}dashboard_charts.json`)
.then((response) => {
responseHandler(response);
});
内,但这种方法是从来没有工作。 'yield auth()'在responseHandler中无效。
任何人都可以建议如何更好地设计这种情况下的代码?