【问题标题】:redux-saga middle-ware how to handle api errorredux-saga 中间件如何处理 api 错误
【发布时间】:2018-09-08 16:10:29
【问题描述】:
我正在使用 redux-saga 中间件。
我有一个登录屏幕,用户在其中提供电子邮件和密码。登录失败 redux 代码如下所示。
export const failure = (state) =>
state.merge({ fetching: false, error: true, login: {} })
向用户显示错误消息(“无效的电子邮件/密码”)的最佳做法是什么。
问题:假设我在状态中使用错误来显示消息,但在登录失败后,如果由于某些其他操作而导致状态发生任何变化,我的代码再次显示相同的错误消息。
【问题讨论】:
标签:
reactjs
react-native
redux-saga
【解决方案1】:
这是我的场景:
1. A User attempts to log in
2. Show popup with an error message
3. A User closes popup and under the hood, I dispatch action to clean current error in the state.
4. A User attempts to log in and can see a new error
基本上,有一个专门的动作将被调度以重置状态中的错误。
【解决方案2】:
向用户显示错误的最佳方法是在您的sagas 状态中维护Alert 处理
这将确保仅在调用 saga 时显示错误消息。
例如
// Your default Saga
export function * yourDemoSaga(action) {
const {yourDemoActions} = action
const response = yield call(yourDemoService, yourDemoActions)
if (response.status >= 200 && response.status <= 299) {
const response = path(['data', 'response'], response)
yield call(Alert.alert, 'Success', 'Message has been successfully set.' )
yield put(YourActions.success())
} else {
yield call(Alert.alert, 'Failure', 'Error Message Set here.' )
yield put(YourActions.failure(' Please refresh or try later.'))
}
}
【解决方案3】:
我在 LoginRedux 中添加了错误显示逻辑:
export const failure = (state) => {
ToastAndroid.showWithGravity('Invalid username/password.', ToastAndroid.SHORT, ToastAndroid.CENTER);
return state.merge({ fetching: false, error: true, login: {} })
}