【问题标题】:How can I get the response from dispatch?我怎样才能得到调度的响应?
【发布时间】:2019-08-25 06:00:52
【问题描述】:

我有一个组件,它有一个表单,此时在提交按钮上执行 clic,我调用一个函数 handleSubmit(它在我的组件上),这个函数通过 dispatch 和这个动作调用一个动作,我调用一个服务(HTTP 请求)。

处理提交

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

我想在我的组件中获得响应以便能够进行验证,但由于请求是异步的,我永远无法获得响应并且只打印一个未定义的变量。如何获得响应同步?或者我需要做什么才能进行验证?

【问题讨论】:

  • 要在组件中使用响应,您还需要做 3 件事:在 ADD_DEVICE_REQUEST 上创建一个 reducer 以更新 redux 状态,创建一个选择器函数来获取您在状态中更改的变量,然后使用 mapStateToProps 函数向组件添加一个等于该选择器结果的道具

标签: javascript reactjs react-redux


【解决方案1】:

请用此代码替换您的代码

处理提交

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

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

            dispatch(actions.addDevice(params)).then((response)=>{
                  console.log(response);
            })
       }
    });
}

actions.addDevice

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

        return 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 } }
}

【讨论】:

    【解决方案2】:
    let response = dispatch(actions.addDevice(params)) 
    

    这是异步的。所以从 console.log() 返回 undefined 也就不足为奇了。 console.log() 甚至在调度过程完成之前执行。使用 promise 或 async await 语法。我建议使用 async-await 语法。

    handleSubmit = (e) => {
       e.preventDefault()
       const { validateFields } = this.props.form;
    
       validateFields(async (err, params) => {
           if (!err) {
                const { user, dispatch } = this.props;
    
                let response =await dispatch(actions.addDevice(params))
                console.log(response); //Response is undefined
           }
        });
    }
    

    【讨论】:

      【解决方案3】:

      你没有返回承诺service.addDevice

      所以你可以使用return service.addDevice... 并在handleSubmit 中使用dispatch(...).then((data) => ...do something with the data...)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 2018-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多