我有一个组件,它有一个表单,现在可以点击提交按钮,我调用一个函数 handleSubmit
(它在我的组件上),这个函数通过 dispatch
和这个 Action ,我调用了一个服务(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;
});
}
我想在我的组件中获得响应以便能够进行验证,但是由于请求是异步的,我永远无法获得响应并且只能打印一个 undefined variable 。如何获得响应同步?或者我需要做什么才能进行验证?
最佳答案
您没有返回 promise service.addDevice
。
因此您可以执行 return service.addDevice...
并在 handleSubmit
中执行 dispatch(...).then((data) = > ...对数据做点什么...)
关于javascript - 我怎样才能得到调度的回应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499695/