我有一个具有某种形式的组件,该组件现在可以对提交按钮进行操作,我调用一个函数handleSubmit(它在我的组件上),该函数通过dispatch调用一个动作,并且该动作服务调用(HTTP请求)。

handleSubmit

handleSubmit = (e) => {
   e.preventDefault()
   const { validateFields } = this.props.form;

   validateFields((err, params) => {
       if (!err) {
            const { user, dispatch } = this.props;

            let response = dispatch(actions.addDevice(params))
            console.log(response); //Response is undefined
       }
    });
}


actions.addDevice

function addDevice(params){
    return (dispatch, getState) => {
        let { authentication } = getState();
        dispatch(request({}));

        service.addDevice(params, authentication.user.access_token)
            .then(
                response => {
                    if(response.status === 201) {
                        dispatch(success(response.data));
                    }
                    return response;
                },
                error => {
                    dispatch(failure(error.toString()));
                    dispatch(alertActions.error(error.toString()));
                }
            )
    }

    function request(response) { return { type: constants.ADD_DEVICE_REQUEST, response } }
    function success(response) { return { type: constants.ADD_DEVICE_SUCCESS, response } }
    function failure(error) { return { type: constants.ADD_DEVICE_FAILURE, error } }
}


service.addDevice

function addDevice(params, token){
    return axios({
        url: 'http://localhost:5000/user/add-device',
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + token},
        data: {
            data1: params.data1,
            data2: params.data2,
            data3: params.data3
        }
    })
    .then(function(response) {
        return response;
    })
    .catch(function(error) {
        return error.response;
    });
}


我希望在组件中获得响应以能够进行验证,但是由于请求是异步的,因此我永远无法获得响应,而仅输出未定义的变量。如何获得响应同步?或者我需要做些什么才能进行验证?

最佳答案

您没有返回诺言service.addDevice

因此,您可以执行return service.addDevice...,在handleSubmit中执行dispatch(...).then((data) => ...do something with the data...)

09-20 20:53