redux-saga中间件如何处理api错误

时间:2018-03-29 16:03:10

标签: reactjs react-native redux-saga

我正在使用redux-saga中间件。 我有一个登录屏幕,用户提供电子邮件和密码。登录失败redux代码如下所示。

export const failure = (state) =>
  state.merge({ fetching: false, error: true, login: {} })

向用户显示错误消息(“无效的电子邮件/密码”)的最佳做法是什么。

问题:假设我在状态中使用错误来显示消息但是在登录失败后如果由于某些其他操作而导致状态发生任何变化,我的代码将再次显示相同的错误消息。

3 个答案:

答案 0 :(得分: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

基本上,有一个专门的动作将被调度以重置状态中的错误。

答案 1 :(得分:1)

向用户显示错误的最佳方式是在Alert州保持sagas处理

这样可确保仅在调用 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.'))
}
}     

答案 2 :(得分:0)

我在LoginRedux中添加了错误显示逻辑:

export const failure = (state) => {
  ToastAndroid.showWithGravity('Invalid username/password.', ToastAndroid.SHORT, ToastAndroid.CENTER);
  return state.merge({ fetching: false, error: true, login: {} })
}