如何在调度动作Redux后调用回调函数

6tqwzwtp  于 2022-11-12  发布在  其他
关注(0)|答案(4)|浏览(174)

我使用ReactRedux并创建了一个函数来登录,但我需要在成功登录后获得回调返回,并将用户重定向到一个页面。
我尝试将函数作为参数传递,但不起作用。
如何在发货行动后获得退货?
第一个
提交

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);
a9wyjsp7

a9wyjsp71#

您的连接中缺少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);

希望对你有帮助:)

2q5ifsrm

2q5ifsrm2#

如果您使用的是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');  
  }
}
yvt65v4c

yvt65v4c3#

如果您需要具有回调功能的操作,我建议使用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

abithluo

abithluo4#

react-redux/redux分派返回一个承诺。如果你想返回一个值或者在分派后确定请求是成功还是错误,你可以这样做

操作示例

export const fetchSomething = () => async (dispatch) => {
    try {
        const response = await fetchFromApi();
        dispatch({
            type: ACTION_TYPE,
            payload: response.value
        });
        return Promise.resolve(response.value);
    } catch (error) {
        return Promise.reject(error);
    }
}

用法

const foo = async data => {
    const response = new Promise((resolve, reject) => {
        dispatch(fetchSomething())
            .then(v => resolve(v)) 
            .catch(err => reject(err)) 
    });
    await response 
        .then((v) => navigateToSomewhere("/", { replace: true }))
        .catch(err => console.log(err));
};

这篇文章是旧的,但希望它会有所帮助

包.json

"react-redux": "^8.0.2"
   "@reduxjs/toolkit": "^1.8.5"

相关问题