【问题标题】:How to call callback function after dispatch action Redux如何在调度动作 Redux 后调用回调函数
【发布时间】:2020-04-26 04:18:31
【问题描述】:

我使用 React Redux 并创建了一个登录函数,但我需要在成功登录后获取回调返回并将用户重定向到页面。

我尝试将函数作为参数传递但不工作。

dispatch 操作后如何获得回报?

Login fun
export const login = (request,cb) => {
           return dispatch => {
                let url = "/api/user/login";
                axios({
                    method: "post",
                    url: url,
                    data: request,
                    config: { headers: { "Content-Type": "multipart/form-data" } }
                })
                    .then(response => {
                        let authState = {
                            isLoggedIn: true,
                            user: response.data
                        };
                        cb();
                        window.localStorage["authState"] = JSON.stringify(authState);
                        return dispatch({
                            type: "USER_LOGIN_FULFILLED",
                            payload: { userAuthData: response.data }
                        });
                    })
                    .catch(err => {
                        return dispatch({
                            type: "USER_LOGIN_REJECTED",
                            payload: err
                        });
                    });
           };
    };

提交

handleLogin(e) {
        this.setState({ showLoader: true });
        e.preventDefault();
        const request = new Object();
        if (this.validator.allValid()) {
            request.email = this.state.email;
            request.password = this.state.password;
            this.props.login(request, () => {
                //get callbach here
                this.props.history.push('/my-space/my_views');
            })

            this.setState({ showLoader: false });

        } else {
            this.setState({ showLoader: false });
            this.validator.showMessages();
            this.forceUpdate();
        }
    }
const mapStateToProps = state => {
    return {
        authState: state
    };
};
const mapDispatchToProps = dispatch => {
    return {
        login: request => dispatch(login(request))
    };
};
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);

【问题讨论】:

    标签: javascript reactjs redux callback


    【解决方案1】:

    您的连接中缺少 cb(...)

    这里是修复

    handleLogin(e) {
            this.setState({ showLoader: true });
            e.preventDefault();
            const request = new Object();
            if (this.validator.allValid()) {
                request.email = this.state.email;
                request.password = this.state.password;
                this.props.login(request, () => {
                    //get callbach here
                    this.props.history.push('/my-space/my_views');
                })
    
                this.setState({ showLoader: false });
    
            } else {
                this.setState({ showLoader: false });
                this.validator.showMessages();
                this.forceUpdate();
            }
        }
    const mapStateToProps = state => {
        return {
            authState: state
        };
    };
    const mapDispatchToProps = dispatch => {
        return {
            login: (request, cb) => dispatch(login(request, cb))
        };
    };
    export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
    

    希望对你有帮助:)

    【讨论】:

    • 我发布了答案,在 mapDispatchToProps 登录中缺少 cb:(request, cb) => dispatch(login(request, cb))
    • 是的,我忘了在 mapDispatchToProps 中添加这个参数,谢谢
    【解决方案2】:

    如果您使用的是redux-thunk,则可以从您的async action 返回Promise

    The function called by the thunk middleware can return a value,
    that is passed on as the return value of the dispatch method.
    In this case, we return a promise to wait for.
    This is not required by thunk middleware, but it is convenient for us.
    

    但我更喜欢为此目的使用useEffectcomponentDidUpdate

    componentDidUpdate(){
      if(this.props.authState.isLoggedIn){
        this.props.history.push('/my-space/my_views');  
      }
    }
    

    【讨论】:

      【解决方案3】:

      如果您需要具有回调功能的操作,我建议使用 Redux Cool 包。

      安装

      npm install redux-cool
      

      用法

      import {actionsCreator} from "redux-cool"
      
      
      const my_callback = () => {
          console.log("Hello, I am callback!!!")
      }
      
      const callbackable_action = actionsCreator.CALLBACKABLE.EXAMPLE(1, 2, 3, my_callback)
      
      console.log(callbackable_action)
      //      {
      //          type: "CALLBACKABLE/EXAMPLE",
      //          args: [1, 2, 3],
      //          cb: f() my_callback,
      //          _index: 1
      //      }
      
      callbackable_action.cb()
      //      "Hello, I am callback!!!"
      
      

      当我们尝试生成一个动作对象时,我们可以将回调函数作为最后一个参数传递。 actionsCreator 会检查,如果最后一个参数是一个函数,它会被认为是一个回调函数。

      详情请见Actions Creator

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-13
        • 1970-01-01
        • 2021-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-16
        • 1970-01-01
        相关资源
        最近更新 更多