我不会用redux-saga
,因为它没有这样做,你需要什么样的能力。
相反,设立专卖店,API层和其他东西的时候配置API层调用做处理上发生的每个错误。
报告API层的示例调用错误处理程序。
const conf = {
onError:() => {},
}
api.onError = (cb) => {
conf.onError = cb;
}
api.get = (url) => {
fetch(url)
.then(response => {
if (response.ok === false) {
return conf.onError(response);
}
return response;
})
// Network error
.catch(conf.onError)
}
配置应用程序。
import store from './store';
// Configure your API wrapper and set error callback which will be called on every API error.
api.onError((error) => {
store.dispatch({
type: 'API_ERROR',
payload: error,
});
});
// In you reducers...
isAuthorized(state, action) {
if (action.type === 'API_ERROR' && action.payload.statusCode === 401) {
return false;
}
return state;
}
然后,调用API为通常情况下,如果发生错误,动作被分配到存储,你可能会或可能不会对这一行动作出反应。