在React生命周期方法

时间:2017-08-19 02:11:53

标签: reactjs redux react-redux graphql

我开发的应用程序具有在用户注册应用程序时验证电子邮件的功能。用户注册时,会生成代码并将链接发送给用户。当用户单击链接时,前端会检入后端以验证代码。如果代码检出,那么"激活" flag在用户数据库中切换,用户被重定向到登录屏幕。

我使用GraphQL作为数据库内容,使用Redux进行状态管理,我的动作如下:

export function confirmActiveUser(token) {
    return function (dispatch) {
        dispatch(activateUserRequest())
        apolloClient.mutate(
            {
                mutation: CONFIRM_EMAIL,
                variables: { token: token }
            }
        ).then((res) => {
            let { error, ok } = res.data.confirmEmail;
            if (ok === true) {
                dispatch(activateUserSuccess())
            } else {
                dispatch(activateUserFailure())
            }
        })
    }
}

,激活页面组件如下所示:

// mapStateToPropsFunction
// mapDispatchToPropsFunction
class MyActivationComponent extends React.Component {
    componentDidMount() {
      this.props.confirmActiveUser(this.props.params.id) // the generated token
    }

    render() {
       <div>
           {this.props.ifIsActivated
              ? // redirect to sign in
              : // do something else
           }
       </div>
    }
}

问题在于,confirmActiveUser操作被调度两次(从而进行2次数据库调用),我认为这是由于状态已更改activateUserRequestactivateUserSuccess导致的-renders。

验证是在页面(或更确切地说,组件加载)时发生,而不是在按下按钮时发生。所以,我基本上试图避免不得不进行多次数据库调用。

导致这些多次调用的原因是什么,以及获取上述操作的首选方法是什么。

非常感谢,非常感谢。

1 个答案:

答案 0 :(得分:0)

如果你确定动作创建者真的从Bool被调用了两次,那么我认为你正在安装两次组件(渲染两次或安装,卸载,重新安装)......

相关问题