处理native native和redux中的错误

时间:2018-02-06 18:45:54

标签: react-native react-redux

我有一个使用redux进行状态管理的本机应用程序。 在每个API请求中,我都调度了由reducer处理的操作。然后将其转发给saga并返回reducer。

我正在使用小吃吧来显示可能发生的任何错误。

e.g。在登录流程中,其中一个操作是获取用户名的OTP。

行动类型是:

  • GET_OTP_FOR_USER_REQUEST
  • GET_OTP_FOR_USER_SUCCESS
  • GET_OTP_FOR_USER_FAILURE

reducer(LoginReducer)的初始状态是

{
    hasError: false,
    error : {
       display_message : "",
       details : null
    }
    otherData : []
}

现在,在GET_OTP_FOR_USER_FAILURE的情况下,reducer将更新为

{
    hasError: true,
    error : {
       display_message : "Invalid Username",
       details : null
    }
    otherData : []
}

在我的视图组件中,我根据hasError标志

有条件地渲染快餐栏
{this.props.hasError ? Snackbar.show({
                title: this.props.error.display_message,
                duration: Snackbar.LENGTH_LONG
            }) : null}

如果我没有重置hasError,那么快餐栏将继续为每个setState调用(在textinputchange上发生)。

我正在使用的当前方法是,我有一个RESET_ERROR的动作。 一旦在组件的文本框上调用setState(在这种情况下是用户名)

,我就会调用此操作
onUserNameTextChanged = (text) => {

    this.props.resetError(); //Reset the error

    this.setState({ //something });

}

这个问题是this.props.resetError();将在每个角色更新时被调用。 为了确保我不多次调用render,我使用的是shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState){
    if(this.props.hasError && (this.props.hasError === nextProps.hasError))
        return false;
    else
        return true;
}

我不确定是否有更简单或更简洁的方法来处理这些情况。任何指示都会有所帮助。

1 个答案:

答案 0 :(得分:1)

如果出现错误,您可以有条件地调用它,这样您就不会总是调用它:

onUserNameTextChanged = (text) => {
    if (this.props.hasError) {
        this.props.resetError(); //Reset the error
    }

    this.setState({ //something });

}

如果您希望在API成功返回之前显示该错误,您也可以将其绑定到成功操作中。